CreateElement with id?

CreateElement with id?

I’m trying to modify this code to also give this div item an ID, however I have not found anything on google, and idName does not work. I read something about append, however it seems pretty complicated for a task that seems pretty simple, so is there an alternative? Thanks 🙂
g=document.createElement(‘div’); g.className=’tclose’; g.v=0;


Solution 1:

You should use the .setAttribute() method:

g = document.createElement('div');
g.setAttribute("id", "Div1");

Solution 2:

You can use = 'desiredId' from your example to set the id of the element you’ve created.

Solution 3:

var g = document.createElement('div'); = 'someId';

Solution 4:

You can use Element.setAttribute




Here’s my function for doing this better:

function createElement(element, attribute, inner) {
  if (typeof(element) === "undefined") {
    return false;
  if (typeof(inner) === "undefined") {
    inner = "";
  var el = document.createElement(element);
  if (typeof(attribute) === 'object') {
    for (var key in attribute) {
      el.setAttribute(key, attribute[key]);
  if (!Array.isArray(inner)) {
    inner = [inner];
  for (var k = 0; k < inner.length; k++) {
    if (inner[k].tagName) {
    } else {
  return el;

Example 1:


will return this:


Example 2:


will return this:

<a href="" style="color:#FFF;background:#333;">google</a>

Example 3:

var google = createElement("a",{"href":""},"google"),
    youtube = createElement("a",{"href":""},"youtube"),
    facebook = createElement("a",{"href":""},"facebook"),
    links_conteiner = createElement("div",{"id":"links"},[google,youtube,facebook]);

will return this:

<div id="links">
    <a href="">google</a>
    <a href="">youtube</a>
    <a href="">facebook</a>

You can create new elements and set attribute(s) and append child(s)

createElement("tag",{attr:val,attr:val},[element1,"some text",element2,element3,"or some text again :)"]);

There is no limit for attr or child element(s)

Related:  Event after modifying polygon in Google Maps API v3

Solution 5:

Why not do this with jQuery?

var newDiv= $('<div/>', { id: 'foo', class: 'tclose'})

Solution 6:

var element = document.createElement('tagname');    

element.className= "classname"; "id";

try this you want.