swapnesh
swapnesh

Reputation: 26732

innerHTML not working with classname in JS

My drop down List to select particular value-

<select name="category" id="category" onChange="showDiv(this.value);" >
    <option value="">Select This</option>
    <option value="1">Nokia</option>
    <option value="2">Samsung</option>
    <option value="3">BlackBerry</option>
    </select>

This is the div where i want to show the text

<span class="catlink"> </span>

And this is my JS function -

    function showDiv( discselect )
    {

    if( discselect === 1)
    {
    alert(discselect); // This is alerting fine
    document.getElementsByClassName("catlink").innerHTML = "aaaaaaqwerty"; // Not working
    }

}

Let me know why this is not working, and what i am doing wrong?

Upvotes: 3

Views: 27049

Answers (2)

KooiInc
KooiInc

Reputation: 122906

You ar creating a nodeList (a special array of Nodes) using getElementsByClassName. Alternatively you can use document.querySelector, which returns the first element with className .catlink:

function showDiv( discselect ) {
    if( discselect === 1)    {
      document.querySelector(".catlink").innerHTML = "aaaaaaqwerty";
    }
}

Upvotes: 4

user1432124
user1432124

Reputation:

document.getElementsByClassName("catlink")is selecting all the elements in webpage as array therefore you have to use [0]

 function showDiv( discselect ) 
 { 

 if( discselect === 1) 
 { 
 alert(discselect); // This is alerting fine 
 document.getElementsByClassName("catlink")[0].innerHTML = "aaaaaaqwerty"; // Now working 
 } 
 }

Upvotes: 17

Related Questions