recursiveTx
recursiveTx

Reputation: 1

How to select an element with dynamic selector?

I want to select a selector using puppeteer and css selectors. The element only has an id. The id is changing everytime i browse the site.

<span id="select-fjva-container">Text</span>

'fjva' is changing everytime i browse the site. So it could be something like 'abc' or 'xyz' on the next browsing. The chars in the middle are totaly random.

Is there a way how i could select it?

I would think of:

const select = document.querySelector('#select2-*-container')

Thanks in advice!

Upvotes: 0

Views: 709

Answers (2)

A Haworth
A Haworth

Reputation: 36457

You can do this with a simple one-line selector - all those ids starting with 'select-' and ending with '-container (this snippet also assumes you want to not select 'select-container' but just drop the :not part if you do want to select it):

const spans = document.querySelectorAll('span[id^="select-"][id$="-container"]:not(#select-container)');
for (let i = 0; i < spans.length; i++) {
  spans[i].style.backgroundColor = 'pink';
}
<span id="select-fjva-container">Text</span>
<span id="select--container">Text</span>
<span id="select-container">Text</span>

Upvotes: 0

Spectric
Spectric

Reputation: 31987

You can select all elements whose id starts with select, then loop through the elements and check the parts:

const startsWith = document.querySelectorAll('[id^=select]')
startsWith.forEach(elem => {
  const parts = elem.id.split("-")
  if(parts[0] == "select" && parts[2] == "container") console.log(elem)
})
<span id="select-abc-container">Correct</span>
<span id="select-def-container">Correct</span>
<span id="select-geh-container">Correct</span>
<span id="select-container">Wrong</span>

Although David Thomas's suggestion to use the starts with & ends with selector is indeed more clever:

const startsWith = document.querySelectorAll('[id^=select-][id$=-container]')
startsWith.forEach(elem => {
  console.log(elem)
})
<span id="select-abc-container">Correct</span>
<span id="select-def-container">Correct</span>
<span id="select-geh-container">Correct</span>

Take note that the above selector will also select elements with class select-container

Upvotes: 2

Related Questions