Queryselector Data Attribute
layout: bpost title: "JavaScript querySelector by data attribute" image: "images/content/updating-angular-cli-projects.png" excerpt: "This example will teach you how to use JavaScript's data attribute with querySelector to select or access an HTML element." categories: [javascript] permalink: /queryselector-data-attribute/
tags: [javascript]
This example will teach you how to use JavaScript's data attribute with querySelector to select or access an HTML element.
Let's take the following HTML elements that have associated data attributes.
<h1 data-header="h1hdr"> Example</h1>
<div data-id="1">Element 1</div>
<div data-id="2">Element 2</div>
We must now select the aforementioned elements in JavaScript based on their data attribute.
You can select the first element using the document.querySelector()
method by providing a [data-attribute = 'value']
as an argument:
const header = document.querySelector("[data-header='h1hdr']");
console.log(header);
If you need to select multiple elements; you must use the document.querySelectorAll()
method as follows:
const elements = document.querySelectorAll("[data-id]");
Join the 10xdev Community
Subscribe and get 8+ free PDFs that contain detailed roadmaps with recommended learning periods for each programming language or field, along with links to free resources such as books, YouTube tutorials, and courses with certificates.