0

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

1
  • please give one example of such li which you want to create. Commented Aug 13, 2021 at 18:27

2 Answers 2

2

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
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thx man, that worked well, but you know how to explain why the .data() on the end didn't worked?
@Dosbodoke No prob. I'm not sure actually. It would seem that using .data should have the same effect. Maybe a jquery expert on here might know
@Dosbodoke Try using the .data(key, value) rather than the .data({object Object}). Maybe it's something with the formatting of that
0

You could try using attr() instead. (See how to add attributes in jquery)
Also check out HTML li data-* attribute.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.