嗨,这是我的问题。
<div id='whatever'>
<p id='1'> I am 5 years old </p>
<p id='3'> my mum is 40 years old </p>
<p id='7'> check out this number 7 </p>
<p id='8'> 78 99 46 </p>
</div>
elem = document.getElementById("whatever").innerHTML;
target_array = elem.match(/???????????/g);
// => target_array = [1,3,7,8]
我找不到一个正则表达式,它为我提供了这个target_array (\ d)(我得到了很多) (\ d)?='(没有工作)
答案 0 :(得分:3)
为什么你只是通过遍历DOM来尝试使用RegExp来实现它:
var ids = Array.from(document.querySelectorAll('#whatever > p'))
.map(item => item.id);
console.log(ids);
<div id='whatever'>
<p id='1'> I am 5 years old </p>
<p id='3'> my mum is 40 years old </p>
<p id='7'> check out this number 7 </p>
<p id='8'> 78 99 46 </p>
</div>
答案 1 :(得分:0)
document.getElementById('but').addEventListener('click', function(ev){
function valid(w) {
return w.innerHTML.match(/check/g);
}
var d = document.getElementById('whatever');
var p = d.querySelectorAll('P');
var f = Array.from(p)
.filter(valid)
.map(item => item.id);
console.log(f);
});
&#13;
<div id='whatever'>
<p id='1'> I am 5 years old </p>
<p id='3'> my mum is 40 years old </p>
<p id='7'> check out this number 7 </p>
<p id='8'> 78 99 46 </p>
</div>
<button id='but'>Test</button>
&#13;