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

Get the ID of element using the starting word of string present in it using jQuery

I know the starting word of the string present in the h2 element. How to find the ID of that element using contains?

The string present inside h2 is ‘What Repairs Can Fix A P0500 Trouble Code?’. The sub string ‘P0500’ varies so it is not known. Is there a way to find the id using only the known words of the string.

const word = 'P0500';
let id = $(`h2:contains(${word})`).attr('id');

console.log(id);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

<h2 id="heading2">What Repairs Can Fix A P0500 Trouble Code?</h2>

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

>Solution :

It’s working fine for me. I added a working snippet for the reference.

let id = $('h2:contains("test")').attr('id');

console.log(id);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<h2 id="1">div1</h2>
<h2 id="2">This is a test, nested in div1</h2>
<h2 id="3">Nested in div1<h2>
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