简体   繁体   中英

How to target element by data attribute using Javascript

I have a div element with a data attribute that I need to use to select that element but I'm drawing a blank on how to do that.

HTML

<div class="element" data-id="123456789"></div>

JS

var element = document.body.querySelector('.element[data-id=123456789]');

您只需要在data-id值上添加""

var element = document.body.querySelector('.element[data-id="123456789"]')

使用此document.body.querySelector(“ div [data-id ='123456789']”);

在属性选择器值中添加引号:

var element = document.body.querySelector('.element[data-id="123456789"]');

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