5

i know that i can create an element such as:

var foo = document.createElement('div');

and to set the div id i would do as such:

foo.setAttribute('id', 'divName');

and if you google long enough you will find someone doing code such as here

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]);

which would equal out to:

var foo = document.createElement('div', {'id':'divName);

yet when i run the above code the id or divName is not added and instead an empty div is created. so i am curious what i am doing wrong, and if it is even possible to both create and set the div name for an element using .createElement only?

3
  • 1
    you have a syntax error on var foo = document.createElement('div', {'id':'divName); should be var foo = document.createElement('div', {'id':'divName'});. was it a typo?
    – bennygenel
    Sep 7, 2017 at 20:03
  • 1
    is the quiestion is using jQuery also?? $('<div id="some_id">') ? Sep 7, 2017 at 20:04
  • Well there is a method there that does it.... Sep 7, 2017 at 20:33

5 Answers 5

21

If you want to add an object in one line, you can use:

Object.assign(document.createElement('div'),{id:"fd"})

here it is in action:

document.body.append(Object.assign(document.createElement('div'),{textContent:"fd"}));

no jquery needed.

2
  • 1
    Object.assign(document.createElement('div'),{id:"fd"})
    – JTL
    Apr 15, 2019 at 17:11
  • $ = (el,attrs) => Object.assign(document.createElement(el),attrs); document.body.appendchild($("div",{id:"id"}));
    – PAEz
    May 10, 2019 at 16:55
4

Well, you can create your own prototype which will do it for you. Not the best solution, but will make you able to create element in one line and add attributes to it:

document.__proto__.customCreateElement = function(tag, attributes){
    var e = document.createElement(tag);

    for(var a in attributes) e.setAttribute(a, attributes[a]);

    return e;
}

And then:

var a = document.customCreateElement('div', {id: "myId", name: "myName"});

results in:

<div id="myId" name="myName"></div>

Of course if you want to make it in pure JavaScript without any frameworks or libraries.

2
  • 1
    if we are writing a function and calling it, instead we can write a normal function. what is the extra benefit to putting it in document? Sep 7, 2017 at 20:16
  • Good point. I was just thinking about overriding createElement prototype but changed my mind and I left it like this Sep 7, 2017 at 20:19
2

    var createElement = function (tagName, id, attrs, events) {
      attrs = Object.assign(attrs || {}, { id: id });
      events = Object.assign(events || {});
      
      var el = document.createElement(tagName);
      Object.keys(attrs).forEach((key) => {
        if (attrs [key] !== undefined) {
          el.setAttribute(key, attrs [key]);
        }
      });
      
      Object.keys(events).forEach((key) => {
        if (typeof events [key] === 'function') {
          el.addEventListener(key, events [key]);
        }
      });

      return el;
    }

    createElement('div');

1

According to the spec , createElement accepts a second option object which only can have the is attribute. Unfortunately nothing for id, class style.. See also the MDN docs

4
  • 1
    This one actually does not work. For me at least. When I print foo it is undefined Sep 7, 2017 at 20:09
  • @Sebastian, yes you are right not the element was assigned to the foo
    – mbehzad
    Sep 7, 2017 at 20:14
  • so sad that we have to create a new line just to assign a div declaration
    – Zach Smith
    Sep 7, 2017 at 20:35
  • This is the only response that actually explains why it doesn't work.
    – tie0ezah
    May 22, 2020 at 22:45
1

If you can use jQuery you can write according to the doc:

$('<div/>', {id: 'divName'})

var ele = $('<div/>', {id: 'divName'});

console.log(ele.get(0).outerHTML);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.