skip to Main Content

I have the below url

<h1 id="header_2" title="mytitle" data-id="header_title" class="sampleclass " xpath="1">mytitle<span aria-label="sometest"   class="sampleclass ">- 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

3

Answers


  1. 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
    
    Login or Signup to reply.
  2. 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'))
      }
    }
    
    Login or Signup to reply.
  3. 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>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search