Search code examples
javascriptjquerycheerio

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>


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>