Reputation: 5674
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?
Upvotes: 6
Views: 17238
Reputation: 564
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.
Upvotes: 24
Reputation: 785
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');
Upvotes: 2
Reputation: 42044
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>
Upvotes: 1
Reputation: 8515
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.
Upvotes: 4