使用 jQuery 使用其中存在的字符串的起始词获取元素的 ID

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

我知道 h2 元素中字符串的起始词。如何使用包含查找该元素的 ID?

h2 中的字符串是 'What Repairs Can Fix A P0500 Trouble Code?'。子字符串 'P0500' 有所不同,因此未知。有没有办法只使用字符串的已知单词来查找 id。

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>

它对我来说很好用。我添加了一个工作片段作为参考。

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>