styler
styler

Reputation: 16501

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]');

Upvotes: 18

Views: 29280

Answers (2)

Sai
Sai

Reputation: 2668

Add quotes to the attribute selector value:

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

Upvotes: 3

Nenad Vracar
Nenad Vracar

Reputation: 122087

You just need to add "" on data-id value

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

Upvotes: 27

Related Questions