简体   繁体   中英

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?

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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM