Changing content of class using Javascript

html, javascript, onclick, tags

Solution

Your x - is array of elements. try to use loop:

<body>

<p class="demo">JavaScript can change the content of an HTML element.</p>    
<p class="demo">Yolo</p>   

<button type="button" onclick="myFunction()">Click Me!</button>

<script>        
function myFunction()
{
x=document.getElementsByClassName("demo");  // Find the elements
    for(var i = 0; i < x.length; i++){
    x[i].innerText="Hello JavaScript!";    // Change the content
    }

}

</script>
</body>

See FIDDLE

Problem

I started reading JavaScript in W3schools and testing out/changing few things in the examples they give so I can see what is doing what but didn't manage to identify the syntax, yet. Below is the original code to change p tag content, the link to it. ``` <p id="demo"> JavaScript can change the content of an HTML element. </p> <script> function myFunction() { x = document.getElementById("demo"); // Find the element x.innerHTML = "Hello JavaScript!"; // Change the content } </script> <button type="button" onclick="myFunction()">Click Me!</button> ``` I want to know how to change contents with the same class, but failed as you can see that the example below doesn't work. Fiddle of code below. ``` <p class="demo"> JavaScript can change the content of an HTML element. </p> <p class="demo">Yolo</p> <script> function myFunction() { x = document.getElementsByClassName("demo"); // Find the element x.innerHTML = "Hello JavaScript!"; // Change the content } </script> <button type="button" onclick="myFunction()">Click Me!</button> ``` If you could show me how ^^" and help me understand, is "getElementById" a variable that could be anything else or is it a command?

Original source