RetroPanda
RetroPanda

Reputation: 99

Javascript. get all element by aria-label

Hey im trying to get every single element on a page that has an aria label that contains/starts with "i_". I also need to do this in javascript.

thanks

Upvotes: 3

Views: 17196

Answers (3)

Gaetano
Gaetano

Reputation: 1150

You can use the document.querySelector[All] method to find your element by css. With css you can filter by attributes. *[aria-label^="value"] would select any elements that have an aria-label which it's value starts with "value".

code:

const node = document.querySelector('*[aria-label^="containing"]');

Upvotes: -1

Matheus Avellar
Matheus Avellar

Reputation: 1515

In CSS, you would use the [attribute^=value] format:

[aria-label^="i_"] {
    background: #55ff55;
}

In JavaScript, just use the same thing:

document.querySelectorAll("[aria-label^='i_']");

That should return an array-like list of all the elements with aria-label values that start with i_.

Here's an example with both of them:

var x = document.querySelectorAll("[aria-label^='i_']");
// 'x' contains all of the <p> elements that have "i_" in the start
[aria-label^="i_"] {
    background: #55ff55;
}
<p aria-label="i_foo"> Giraffes have black tongues to protect them from getting sunburnt </p>
<p aria-label="i_bar"> Coral colonies can live up to centuries old </p>
<p aria-label="m_foo"> The moon is a planet </p>
<p aria-label="i_gaw"> Ostriches' eyes are larger than their brains </p>

Upvotes: 7

kind user
kind user

Reputation: 41893

Catch all specified elements, iterate over them and check if it's aria-label attribute starts with i_. If so - push it into newly made arr.

var elems = document.getElementsByClassName('elem');
var arr = [];

Array.from(elems).forEach(v => v.getAttribute('aria-label').startsWith('i_') ? arr.push(v) : v);

console.log(arr);
<div aria-label='i_one' class='elem'></div>
<div aria-label='i_two' class='elem'></div>
<div aria-label='three' class='elem'></div>

Upvotes: 3

Related Questions