最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - innerHTML not working with classname in JS - Stack Overflow

programmeradmin4浏览0评论

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?

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?

Share Improve this question asked Jun 1, 2012 at 5:55 swapneshswapnesh 26.7k24 gold badges96 silver badges129 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 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 
 } 
 }

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";
    }
}
发布评论

评论列表(0)

  1. 暂无评论