简体   繁体   English

Appendchild基于数据属性

[英]Appendchild based on data-attribute

I've got a few divs like this: 我有几个像这样的div:

<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: 我想在data-order = 1的特定div中添加一些内容.Javascript代码:

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

This will add it to both divs. 这会将它添加到两个div中。 But I only want to add the content to div number 1. How can I make this happen? 但我只想将内容添加到div 1中。我怎样才能实现这一目标?

First of id should be unique in the DOM so you need to fix that. 第一个idDOM应该是唯一的,因此您需要修复它。

Maybe switch to using class that will work. 也许切换到使用可以工作的class

Then use css selector syntax. 然后使用css选择器语法。

 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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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