I want to create multiple divs using a for loop
which i do it like this
for(let i = 0; i < data.length; i++) {
let divs = document.createElement('div');
divs.className = 'button';
divs.data-id = (data[i]).id; // error
document.body.appendChild(divs);
}
Now my issue is that data-id
is required but it pops an error. So how can I define data-id
dynamically
I also tried giving the whole div as innerHTML of another div but then it wont render. So how can this be solved??
I want to create multiple divs using a for loop
which i do it like this
for(let i = 0; i < data.length; i++) {
let divs = document.createElement('div');
divs.className = 'button';
divs.data-id = (data[i]).id; // error
document.body.appendChild(divs);
}
Now my issue is that data-id
is required but it pops an error. So how can I define data-id
dynamically
I also tried giving the whole div as innerHTML of another div but then it wont render. So how can this be solved??
Share Improve this question asked Mar 16, 2017 at 7:01 iamsakshamiamsaksham 2,9494 gold badges30 silver badges52 bronze badges 1- See this: stackoverflow./a/23899918/4964262 – jkythc Commented Mar 16, 2017 at 7:09
4 Answers
Reset to default 4Use setAttribute()
instead:
divs.setAttribute('data-id' , data[i].id);
Also note that hyphens are not allowed in Javascript identifiers, they would be parsed as substraction.
You're looking for divs.setAttribute('data-id', data[i].id);
.
If you were trying to read an attribute with a funky character such as that dash in your example, you would access it with brackets instead of dot notation and quote the attribute like so: divs.attributes['data-id']
This should work:
for(let i = 0; i < data.length; i++) {
let divs = document.createElement('div');
divs.setAttribute("id", "btn_id");
divs.setAttribute("class", "btn_class");
divs.setAttribute("data-id", (data[i]).id);
document.body.appendChild(divs);
}
Or use Jquery alternatives:
var newDiv= $('<div/>', { id: 'foo', class: 'tclose'})
for(let i = 0; i < data.length; i++) {
let divs = document.createElement('div');
var attr = document.createAttribute('data-id');
attr.value = (data[i]).id;
divs.setAttributeNode(attr);
document.body.appendChild(divs);
}