Find an Element in Dom Based on an Attribute Value

Find an element in DOM based on an attribute value

Update: In the past few years the landscape has changed drastically. You can now reliably use querySelector and querySelectorAll, see Wojtek's answer for how to do this.

There's no need for a jQuery dependency now. If you're using jQuery, great...if you're not, you need not rely it on just for selecting elements by attributes anymore.


There's not a very short way to do this in vanilla javascript, but there are some solutions available.

You do something like this, looping through elements and checking the attribute

If a library like jQuery is an option, you can do it a bit easier, like this:

$("[myAttribute=value]")

If the value isn't a valid CSS identifier (it has spaces or punctuation in it, etc.), you need quotes around the value (they can be single or double):

$("[myAttribute='my value']")

You can also do start-with, ends-with, contains, etc...there are several options for the attribute selector.

Get an element by using it's attribute value

Use this selector instead: [title="M\'affecter cette demande"]

var elem = document.querySelector('[title="M\'affecter cette demande"]');

console.log(elem);
<a href="javascript:void(0);" title="M'affecter cette demande" data-aura-rendered-by="1314:0" class="forceActionLink" data-aura-class="forceActionLink">

<div class="slds-truncate" title="M'affecter cette demande" data-aura-rendered-by="1315:0">M'affecter cette demande</div>

</a>

Find a DOM Element using an attribute-value which is acquired dynamically?

The string concatenation inside querySelector is wrong

It should be working with this below code for that line

const two = document.querySelector(`[index="${twoi}"]`);

Javascript to get elements by its attribute

store each element in a array the loop throught each element, and if the element contains the attribute someAttribute do somgthing.

var arr_elms = [];
arr_elms = document.body.getElementsByTagName("*");
var elms_len = arr_elms.length;

for (var i = 0; i < elms_len; i++) {
if(arr_elms[i].getAttribute("someAttribute") != null){
alert("FOUND : " + arr_elms[i].getAttribute("someAttribute"));
}
}

Select an object property within an attribute of the DOM

First, note that document.querySelectorAll returns a list of elements that match the given query, not a list of the values of attributes of those elements that you specify in the query.

From const users = document.querySelectorAll('a[metadata]'), you can get the metadata attribute of, say, the first element, like so:

const metadata0 = users[0].getAttribute("metadata");

And then, since it's a JSON string, you parse it:

const user0 = JSON.parse(metadata0);

Now you can use user0 like a regular JavaScript object:

user0.username
// johnny134

P.S. The JSON in the metadata attribute is not valid, and you may get an error when you try to parse it. Use double quotes in JSON, not single quotes.

Getting element by a custom attribute using JavaScript

It is not good to use custom attributes in the HTML. If any, you should use HTML5's data attributes.

Nevertheless you can write your own function that traverses the tree, but that will be quite slow compared to getElementById because you cannot make use of any index:

function getElementByAttribute(attr, value, root) {
root = root || document.body;
if(root.hasAttribute(attr) && root.getAttribute(attr) == value) {
return root;
}
var children = root.children,
element;
for(var i = children.length; i--; ) {
element = getElementByAttribute(attr, value, children[i]);
if(element) {
return element;
}
}
return null;
}

In the worst case, this will traverse the whole tree. Think about how to change your concept so that you can make use browser functions as much as possible.

In newer browsers you use of the querySelector method, where it would just be:

var element = document.querySelector('[tokenid="14"]');

This will be much faster too.


Update: Please note @Andy E's comment below. It might be that you run into problems with IE (as always ;)). If you do a lot of element retrieval of this kind, you really should consider using a JavaScript library such as jQuery, as the others mentioned. It hides all these browser differences.

Select element by attribute without jQuery

Simply use document.querySelector() for one result or document.querySelectorAll() for a NodeList result.

https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector

https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll

document.querySelector('[data-attr=this]').style.backgroundColor = 'red';
<div>not this one</div>
<div data-attr="this">this one</div>


Related Topics



Leave a reply



Submit