1

I want to use JavaScript to find a specific HTML element by the number of characters in its id attribute.

For example if the element I want to find looks like this:

<element id="12345678"></element>

And has 8 characters in its id attribute, how would I find this element.

Some basic pseudo code I imagine would look like this:

[e] = document.GetElementById where id.charLength == 8

And this would return an array with all elements on the page whose id attribute is 8 characters long.

In case anyone asks, I cannot just use the id to get the element because the id changes with every page refresh. Xpath will not work either as the element changes its position in the DOM with every refresh. There are no constant identifying attributes of the element's parents either.

The only constant is the length of the id attribute of this specific element, and so I have concluded that this is the only way to grab the element.

Luke
  • 17
  • 4

4 Answers4

1

You could use Document.querySelectorAll() with an attribute selector to find all elements on the page that have an id attribute (with any value) and then use Array.prototype.filter() (and Array.from()) to filter them according to their id's length:

console.log(Array.from(document.querySelectorAll('[id]'))
  .filter(element => element.id.length === 3));
  
console.log(Array.from(document.querySelectorAll('[id]'))
  .filter(element => element.id.length === 6));
  
<div></div>
<div id="123"></div>
<div id="456"></div>
<div id="123456"></div>
<div id="987654"></div>
Danziger
  • 19,628
  • 4
  • 53
  • 83
0

Try Javascript: How to loop through ALL DOM elements on a page? to loop through all elements and then set your own criteria (for the id length) during that loop

Yakko Majuri
  • 448
  • 3
  • 13
0

You can do first get all the dom elements by using document.getElementsByTagName("*") and then use find to get the required dom element

const domElements = document.getElementsByTagName("*");
const required = [...domElements].find(element => element.id.length === 8);
Abito Prakash
  • 4,368
  • 2
  • 13
  • 26
0

Here is the solution in pure xpath.

//element[string-length(@id)=8]

enter image description here

supputuri
  • 13,644
  • 2
  • 21
  • 39