I have the below url
<h1 id="header_2" title="mytitle" data-id="header_title" xpath="1">mytitle<span aria-label="sometest" >- Saved</span></h1>
Based in the id(header_2)I wabt to fetch title. My id may also contains like this id="header_mdfa3fad" but for sure after "_" it is numeric.HOw do I write querySelector for it
CodePudding user response:
You can apply regex to filter like this
var divs = [].slice.call(document.querySelectorAll("[id^='header_']")).filter(function(el){
return el.id.match(/^header_[0-9] /i);
});
console.log(divs);
<div id="header_1"></div>
<div id="header_2"></div>
<div id="header_3"></div>
<div id="header_abc"></div>
<div id="header_xyz"></div>
CodePudding user response:
You can use this solution:
const headers = document.querySelectorAll("[id^='header_']");
const titles = [];
headers.forEach((header) => titles.push(header.getAttribute('title')));
// Do something you want with titles array
CodePudding user response:
If I understand you correctly, try something like this:
#select h1 elements with id attribute whose value begins with "header"
headers = document.querySelectorAll("[id^='header_']");
#loop through the elements and extract the part of the attribute value following "_"
for (let header of headers) {
target = header.getAttribute('id').split('_')[1]
#check for the presence of a digit
if (/\d/.test(target)) {
console.log(header.getAttribute('title'))
}
}