Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to target element by data attribute using Javascript

Tags:

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]');
like image 424
styler Avatar asked Dec 28 '16 11:12

styler


People also ask

How do you select an element with a data attribute?

To select the single element, we need to use document. querySelector() method by passing a [data-attribute = 'value'] as an argument.

What is data attribute in JavaScript?

The data-* attribute gives us the ability to embed custom data attributes on all HTML elements. The stored (custom) data can then be used in the page's JavaScript to create a more engaging user experience (without any Ajax calls or server-side database queries).

How do you target a HTML tag in JavaScript?

To select an HTML ID using JavaScript we need to point to it and then store it as a variable. Here is the one line of JavaScript we need to target this element and store it as a variable: Code from a text editor: const chocolateDescription = document. getElementById('chocolateCupcake');


2 Answers

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

var element = document.body.querySelector('.element[data-id="123456789"]')
like image 168
Nenad Vracar Avatar answered Oct 19 '22 22:10

Nenad Vracar


Add quotes to the attribute selector value:

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

like image 21
Sai Avatar answered Oct 19 '22 21:10

Sai