Harlequin
Harlequin

Reputation: 389

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?

Upvotes: 14

Views: 65790

Answers (3)

melvas
melvas

Reputation: 2356

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

Upvotes: 25

Milos Sretin
Milos Sretin

Reputation: 1748

It is easier to use jQuery with Javascript

See this example: http://jsfiddle.net/37jq9/3/

If you use jquery instead of calling

x=document.getElementsByClassName("demo");

you can use

x = $('.demo');

but you can just call the function like this:

$(document).ready(function(){
    $('button').click(function(){
        $('.demo').text('Hello Javascript');
    })   
})

Upvotes: 3

Anonymous
Anonymous

Reputation: 12017

Notice how when you use:

x=document.getElementsByClassName("demo"); 

It is Elements instead of Element. This is because it returns an array a HTMLCollection of all the elements with one particular class name. In order to combat this, you can choose the first element in the array:

x=document.getElementsByClassName("demo")[0];

Upvotes: 4

Related Questions