Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing content of class using Javascript

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?

like image 466
Harlequin Avatar asked Feb 03 '26 19:02

Harlequin


1 Answers

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

like image 112
melvas Avatar answered Feb 05 '26 08:02

melvas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!