Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
47
rated 0 times [  51] [ 4]  / answers: 1 / hits: 59370  / 10 Years ago, sun, february 16, 2014, 12:00:00

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?


More From » html

 Answers
0

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


[#72501] Friday, February 14, 2014, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ammonderekm

Total Points: 247
Total Questions: 105
Total Answers: 98

Location: Tuvalu
Member since Sat, Feb 11, 2023
1 Year ago
;