Explain Codes LogoExplain Codes Logo

Getting HTML elements by their attribute names

html
attribute-selectors
css3-selectors
javascript-dom
Anton ShumikhinbyAnton Shumikhin·Aug 26, 2024
TLDR

To quickly retrieve elements by attribute, use CSS with [attribute] for any value, or [attribute="value"] for a specific value:

[data-attribute] { color: red; }

In JavaScript, fetch all elements sharing a particular attribute using querySelectorAll:

// This line is like the "Avada Kedavra" spell in JavaScript, instead of killing, it finds... everything! let customElements = document.querySelectorAll('[data-attribute]');

Thirsty for a jQuery one-liner? Use $('[attribute]'):

let $customElements = $('[data-attribute]');

Tagging along: Combining tag names and attributes

For narrower selection, concat attribute selectors with tag names. Ideal for reducing unwanted collateral damage – I meant, unrelated elements sharing the same attribute:

// All <a> elements having 'href' attribute, because, well, some don't link to anything (ಠ_ಠ) let anchorElements = document.querySelectorAll('a[href]');

Solo artist: Getting the first matching element

Need just the first matching element? Use querySelector instead:

// Find the first data-attribute in its natural habitat let firstCustomElement = document.querySelector('[data-attribute]');

Dynamic attribute checks: Loop through the DOM

To dynamically validate attribute existence per element, arm yourself with JavaScript:

// Going on a treasure hunt (probably won't find the One Ring though) Array.from(document.getElementsByTagName('*')).forEach(element => { if(element.hasAttribute('data-attribute')) { console.log('Found one!'); } });

Compatibility alert: Keep an eye on browser versions

Remember, querySelectorAll shook hands with IE starting version 8. Nevertheless, ensure a modern browser setting for smooth CSS3 selector operation.

jQuery: The swiss knife for attribute selections

When vanilla JavaScript becomes clumsy, jQuery lends an elegant hand. Especially when your project is already harnessing its power:

// It's like finding Waldo, but with divs let $infoElements = $("div[data-attribute*='value']");

Added insight: More complex situational handling

Collection efficiency with tag names

Add a tag name to your attribute selector mission when dealing with a crowded DOM:

// Because looking after a rogue data attribute is hard when you've got a sea of nodes glaring at you. let paragraphElements = document.querySelectorAll('p[data-mark]');

Case sensitivity: It matters

Keeping in mind that HTML5 attribute names are case-insensitive, be aware that attribute values are sensitive souls:

/* Because 'data-mark' knows the difference between shouting and normal talk */ [data-mark="FRAGILE" i] { border: solid 2px red; }

Dynamic makeup with pseudo-classes

Pseudo-classes in a mix with attribute selectors:

/* To gently scream at the user when they go wrong */ input[type="email"]:invalid { border: solid 2px red; }

Hunting for attribute presence or values

There's a difference between the presence and value of an attribute:

// It's not about the money, but the principle! document.querySelectorAll('[data-mark]'); document.querySelectorAll('[data-mark="valuable"]');