skip to Main Content

For example turning every <p>thing to assign id to</p> in the document into <p id="something">thing to assign id to</p>

this is my first question so pls point out anything I should include

I have not tried anything yet because I dont know how to do it.

2

Answers


  1. To literally answer your question, with the comment I made as a preface, you can grab all the p elements, filter for the ones with desired text, then change their ids using js.

    I updated answer to add a class to the element instead of changing their id.

    example:

    const targetText = "target text";
    const allParagraphElements = document.querySelectorAll("p");
    const pElementArray = Array.from(allParagraphElements);
    const targetPs = pElementArray.filter(el => el.innerText == targetText);
    targetPs.forEach(el => el.classList.add("target"));
    .target {
      font-weight: bold;
    }
    <p>I have text</p>
    <p>I also have text</p>
    <p>I also have text</p>
    <p>target text</p>
    <p>I also have text</p>
    <p>target text</p>
    Login or Signup to reply.
  2. It’s as simple as using the loop counter itself…

    var S='the text';
    
    var P=document.getElementsByTagName('P');
    
    for(var i=0; i<P.length; i++){
    
     if(P.innerHTML==S){P[i].id='P'+i;}
    
    
    }
    

    You’ll end up with IDs that look like… P0, P1, P2, P3, etc

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search