Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to createElement with an id in one line

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?

like image 415
Zach Smith Avatar asked Sep 07 '17 20:09

Zach Smith


People also ask

What is document createElement (' a ')?

In an HTML document, the document.createElement() method creates the HTML element specified by tagName, or an HTMLUnknownElement if tagName isn't recognized.

How we can set an ID to an element?

To create an element and assign an id we can use document. createElement() and then appendChild() .

How do I append a child ID?

2) Moving a node within the document example Second, select the first child element from the first list. Third, select the second element by its id ( second-list ) using the querySelector() method. Finally, append the first child element from the first list to the second list using the appendChild() method.


1 Answers

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.

like image 109
merlin Avatar answered Oct 26 '22 14:10

merlin