Coder Perfect

CreateElement with id?

Problem

I’m trying to change this code to include an ID for this div item, but I can’t find anything on Google, and idName doesn’t work. I read about append, but it appears to be somewhat hard for a seemingly basic activity, so is there another option? Thank you:)

g=document.createElement('div'); g.className='tclose'; g.v=0;

Asked by pufAmuf

Solution #1

Use the.setAttribute() function instead:

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

Answered by lkaradashkov

Solution #2

To set the id of the element you’ve built, use g.id = ‘desiredId’ from your example.

Answered by g.d.d.c

Solution #3

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

Answered by raina77ow

Solution #4

Element is an option. setAttribute

Examples:

g.setAttribute(“id”,”yourId”)

g.setAttribute(“class”,”tclose”)

Here’s how I’m going to do it 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) {
      el.appendChild(inner[k]);
    } else {
      el.appendChild(document.createTextNode(inner[k]));
    }
  }
  return el;
}

Example 1:

createElement("div");

will return this:

<div></div>

Example 2:

createElement("a",{"href":"http://google.com","style":"color:#FFF;background:#333;"},"google");`

will return this:

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

Example 3:

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

will return this:

<div id="links">
    <a href="http://google.com">google</a>
    <a href="http://youtube.com">youtube</a>
    <a href="http://facebook.com">facebook</a>
</div>

You can add new elements, set attribute(s), and append children to them (s)

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

There are no restrictions on attr or child elements (s)

Answered by Guja1501

Solution #5

Why not use jQuery for this?

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

Answered by Shyju

Post is based on https://stackoverflow.com/questions/9422974/createelement-with-id