Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

JS Select dynamic id by pattern

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?

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading