Home > Back-end >  How to select an element with dynamic selector?
How to select an element with dynamic selector?

Time:12-18

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!

CodePudding user response:

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

CodePudding user response:

You can select by using a wildcard, though this won't work if there are multiple elements with a similar type of id. Here is a code reference for you.

const select = document.querySelector('[id^="select2-"][id$="-container"]');

This will select the element with an ID that starts with select2- and ends with -container.

  • Related