Click here to Skip to main content
15,352,321 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I want to change the content of two p tags out of four p tags.
All of the the p tags are having same class.
I want to change the content by classname.

I tried using array of list elements.

What I have tried:

I tried for list.

<!DOCTYPE html>




  • Tea
  • Tea
  • Tea
  • Tea


Try it


function myFunction() {
var list = document.getElementsByClassName("example")[0];
list.getElementsByClassName("child")[0].innerHTML = "Milk";
list.getElementsByClassName("child")[2].innerHTML = "Coffee";
}
Posted
Updated 19-May-17 0:50am
Comments
Mehedi Shams 17-May-17 1:08am
   
Hi Member 13205250,

You said all the paragraph elements use the same class, but I see you are using two classes - "example" and "child". This is confusing. Are you using nested paragraphs? Please post your HTML code and explain a bit more.

var p = document.getElementsByTagName("p");
for(var i=0;i<p.length; i++) {
    if(p[i].innerHTML == "Tea") {
        p[i].innerHTML = "Milk";
        break;
    }
}


<pre>var p = document.getElementsByTagName("p");
for(var i=2;i<p.length; i++) {
    if(p[i].innerHTML == "Tea") {
        p[i].innerHTML = "Coffee";
        break;
    }
}
   
v2
Rethink how you do things.

1 - give your <p> elements id's.
2 - getElementById("the_id_you_set").innerHTML='coffee'
3 - done.

Works for essentially all elements.

When you start using AJAX, this becomes essential.

   
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900