thing to assign id to

this is my first question so p" /> thing to assign id to

this is my first question so p" /> thing to assign id to

this is my first question so p"/>

how to assign an id to every <p> with a specific bit of text inside?

86 Views Asked by At

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

There are 2 best solutions below

1
async await On

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>

0
passingthrough On

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