innerHTML not working with classname in JS

早过忘川 提交于 2019-12-19 10:43:48

问题


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?


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/10845109/innerhtml-not-working-with-classname-in-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!