0

For example:

<p> 1 </p>
<p> 2 </p>
<p> 3 </p>

As you can see that, there are 3 paragraph tag with the different number. So, using JavaScript read the content of the p tag and changed the text according to the content received from the p tag.

Suppose, first p tag has content 1 so changed it into "active". Second p tag has content 2 so changed it into "deactivated" with that third tag contain 3 so changed it into "others".

Where output seems like:

<p> Active </p>
<p> Deactivated </p>
<p> Others </p>

Even if we changed the p tag order to this:

<p> 2 </p>
<p> 3 </p>
<p> 1 </p>

the output must be:

<p> Deactivated </p>
<p> Others </p>
<p> Active </p>

2 Answers 2

1

Use an array with the values you need, for each paragraph convert the original textValue to a number and retrieve the value from the array using that number.

Or use some kind of templating.

const values = [`Active`, `Deactivated`, `Others`];
document.querySelectorAll(`p`).forEach( (p) =>
  p.textContent = values[+(p.textContent.trim()) - 1]);
<p> 1 </p>
<p> 3 </p>
<p> 2 </p>
<p> 3 </p>
<p> 1 </p>
<p> 2 </p>

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

Comments

0

You can use switch and .innerText

const pEles = [...document.querySelectorAll("p")];

pEles.forEach(ele => {
  switch (ele.innerText) {
    case "1":
      ele.innerText = "Active"
      break;
    case "2":
      ele.innerText = "Deactivated"
      break;
    case "3":
      ele.innerText = "Others";
      break;
  }
})
<p>1</p>
<p>2</p>
<p>3</p>

2 Comments

Thank you so much as this one help me better to understand
you can create a hash like > var hash = { '1' : 'Active', '2' : 'Deactivated', '3': 'Others' } and then use this hash instead of switch case like this : ele.innerText = hash[ele.innerText]

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.