Coder Perfect

CreateElement with id?


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 = ‘desiredId’ from your example.

Answered by g.d.d.c

Solution #3

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

Answered by raina77ow

Solution #4

Element is an option. setAttribute




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) {
    } 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 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