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]');
To select the single element, we need to use document. querySelector() method by passing a [data-attribute = 'value'] as an argument.
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).
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');
You just need to add ""
on data-id
value
var element = document.body.querySelector('.element[data-id="123456789"]')
Add quotes to the attribute selector value:
var element = document.body.querySelector('.element[data-id="123456789"]');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With