3

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?

2 Answers 2

17

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 
 } 
 }
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks for the code and solution, just one more to add, i need to replace "===" to "==" to make my code working fine. kindly explain it little further the use of [0] as i was totally unaware of this
[0] will select the first element on the webpage having class catlink
So now if i have more than span classes named catlink on my page then can i insert text using those [0] , [1] ?? ..wow thats really g8 info :)
you can also get the total no. of element by document.getElementsByClassName("catlink").length
Perfect, it works! :) Simple and nice explanation.
4

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";
    }
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.