Home > Software design >  JS Select dynamic id by pattern
JS Select dynamic id by pattern

Time:12-26

Is it possible to select a dynamic ID. I have a page where I have a block with the id pattern <div id="post-id-{1,2,3,...}">...</div>. Since there is a different ID for each post in the detail view, I can't tell in advance which ID it will be. Nevertheless I want to select the block. Can I do something like passing a regex like \poll-id-(id)\ to querySelector? Or do I have to store the post ID somewhere to build my querySelector string from it?

CodePudding user response:

You can use startsWith attribute selector:

document.querySelector("[id^='post-id']")

contains

document.querySelector("[id*='post-id']")

or the whole thing, but then you need to escape the curlies and other characters the selector does not like

https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector

const id = CSS.escape(`post-id-{1,2,3,4}`)
console.log(id,document.querySelector(`[id=${id}]`).textContent)
<div id="post-id-{1,2,3,4}">Div with nasty ID</div>

  • Related