Get Elements by Attribute When Queryselectorall Is Not Available Without Using Libraries

Get elements by attribute when querySelectorAll is not available without using libraries?

You could write a function that runs getElementsByTagName('*'), and returns only those elements with a "data-foo" attribute:

function getAllElementsWithAttribute(attribute)
{
var matchingElements = [];
var allElements = document.getElementsByTagName('*');
for (var i = 0, n = allElements.length; i < n; i++)
{
if (allElements[i].getAttribute(attribute) !== null)
{
// Element exists with attribute. Add to array.
matchingElements.push(allElements[i]);
}
}
return matchingElements;
}

Then,

getAllElementsWithAttribute('data-foo');

queryselector get elements where attribute starts with 'xxx'

You can use xpath for such a task

e.g. to get all attributes that start with xxx- you use the xpath string

'//*/attribute::*[starts-with(name(), "xxx-")]'

or, shorthand for attribute:: is @ - which makes the above

'//*/@*[starts-with(name(), "xxx-")]'

quick sample code

var nodesSnapshot = document.evaluate('//*/attribute::*[starts-with(name(), "xxx-")]', document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var attr;
for (var i=0; i < nodesSnapshot.snapshotLength; i++ ) {
attr = nodesSnapshot.snapshotItem(i);
console.log(attr, attr.ownerElement)
});

Further reading: XPATH on MDN

I haven't found a reliable source for more detailed documentation. document.evaluate is available in all browsers except IE, however, I do recall there is a library for xpath for IE - not sure how complete it is

google wicked good xpath

which is based on

javascript-xpath

How to use querySelectorAll only for elements that have a specific attribute set?

You can use querySelectorAll() like this:

var test = document.querySelectorAll('input[value][type="checkbox"]:not([value=""])');

This translates to:

get all inputs with the attribute "value" and has the attribute "value" that is not blank.

In this demo, it disables the checkbox with a non-blank value.

select id contain slash with querySelectorAll is not working

You can escape the / using \\.

<h2 id="example/123">A heading</h2>

<script>
document.querySelectorAll("#example\\/123");
</script>

Duplicate of CSS selector to select an id with a slash in the id name?

However in this case you are using an id, so you can get the specific element without needing to get it from the NodeList using document.getElementById(), as only one element should have that id.

document.getElementById("hello/world");

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.

Select elements with data attribute *not* using jQuery

It's simply this:

var elements = document.querySelectorAll('[data-mydata]');

How to find a div element by attribute?

If you're using jQuery (upon request), then you can do $('div[guidedhelpid=friendsuggestions]')

For pure javascript, you can use this function to return an array of elements that contain that attribute name:

function getElementsByAttributeName(attr) {
var arr_elms = document.body.getElementsByTagName("*"),
elms_len = arr_elms.length,
return_arr = [];

for (var i = 0; i < elms_len; i++) {
if(arr_elms[i].getAttribute(attr) != null){
return_arr.push(arr_elems[i]);
}
}

return return_arr;
}

Clicking on an attribute in the table Javascript

You can simply use document.querySelector():

document.querySelector('[data-day="03.06.2020"]').click()


Related Topics



Leave a reply



Submit