Search code examples
javascriptnode.jselectronappendchild

Appendchild based on data-attribute


I've got a few divs like this:

<div id="thisisme" data-order="1">
<div id="thisisme" data-order="2">

I want to add some content to the specific div with data-order = 1. The Javascript-code:

var hello = document.getElementById('thisisme');
thisisme.textContent = "blabla"; 
hello.appendChild(thisisme);

This will add it to both divs. But I only want to add the content to div number 1. How can I make this happen?


Solution

  • First of id should be unique in the DOM so you need to fix that.

    Maybe switch to using class that will work.

    Then use css selector syntax.

    const hello = document.querySelector('.thisisme[data-order="1"]');
    hello.innerText = "blabla"; 
    <div class="thisisme" data-order="1">1</div>
    <div class="thisisme" data-order="2">2</div>