0

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.

1
  • “Insert Adjacent HTML” might help here. Commented Oct 26, 2020 at 10:50

1 Answer 1

4

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>

Sign up to request clarification or add additional context in comments.

4 Comments

Strangely, it's actually displaying the javascript itself as in: ${p.id}: ${p.textContent}
Did you use single or double quotes instead of backticks `?
I used single, like '
that won't work. You need to use template literal using backticks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.