Reputation: 336
I am building a script to create a table of content dynamically, I am setting the dataset attribute on each header and creating a li
element with the name of this header, but I also need to insert a data attribute on my li
item, this is not working
function createSummary() {
const summary = $('#summary')
for (let i = 0; i < headers.length; i++) {
let header = headers[i]
header.dataset.header = i
$('<li/>', {
text: header.innerText,
// HERE IS WHERER I NEED HELP
data: {'to': i},
}).appendTo(summary);
}
}
i also tried to put right before the appendTo }).data({'to': i}).appendTo(summary);
Upvotes: 0
Views: 45
Reputation: 364
You could try using attr() instead. (See how to add attributes in jquery)
Also check out HTML li data-* attribute.
Upvotes: 0
Reputation: 1065
https://api.jquery.com/attr/#attr2
Use the .attr
method
function createSummary() {
const summary = $('#summary')
for (let i = 0; i < headers.length; i++) {
let header = headers[i]
header.dataset.header = i
$('<li/>', {
text: header.innerText,
// HERE IS WHERER I NEED HELP
//data: {'to': i},
}).attr('data-to', i).appendTo(summary); //<-- here is the change
}
}
Upvotes: 2