need to set a data-* with no value with vanilla js

52 Views Asked by At

i'm creating a list of links dinamically from the sections i have:

$sections.forEach(({ id, firstElementChild: { textContent } }) => {
    const link = document.createElement('a');
    link.classList.add('link');
    link.setAttribute('href', `#${id}`);
    link.setAttribute('data-scroll-spy', true);
    link.textContent = textContent;
    fragment.appendChild(link);

i need to put a data-scroll-spy to each of thems, but with NO value. i need to have receive this:

<a class="link" href="#" data-scroll-spy>some text</a>

the only solution i ve found by far is with setAttribute but it is not what i expect to,

1

There are 1 best solutions below

0
FrankieD On

setAttribute() takes a string as a second argument, not a boolean.

Set the value to an empty string rather than a boolean and you will achieve your desired result. link.setAttribute('data-scroll-spy', '')