user2029763
user2029763

Reputation: 143

How to use JavaScript to display id of an HTML element

I have html that contains many paragraph tags with an id such as the following:

<p id="123">some text</p>

What I want to do, is to display the id value within the p tag, preferably bolded.

So the above would create html of:

<p id="123"><b>123</b>: some text</p>

Any code samples that I have seen so far require that you already know the id or class value.

How do I do this with JavaScript? Thank you.

Upvotes: 0

Views: 944

Answers (1)

Yousaf
Yousaf

Reputation: 29282

Select all the p elements using querySelectorAll("p") and then iterate over the returned collection and set the content of each p element using the .innerHTML property.

To set the content of each p element correctly, you need to concatenate the contents of each p element with its id. To make the id bold, you can wrap it in strong tag.

const pTags = document.querySelectorAll('p');

pTags.forEach(p => {
    p.innerHTML = `<strong>${p.id}: </strong>${p.textContent}`
});
<p id="123">Some Text</p>
<p id="456">Some Text</p>
<p id="789">Some Text</p>

Upvotes: 4

Related Questions