当前位置: 动力学知识库 > 问答 > 编程问答 >

html - Setting width dynamically for two divs with same id

问题描述:

I have two or three div elements with same id. Here am setting width dynamically using the following javascript:

function SetWidthRPanelAssessments() {

for (var i = 0; i < $("div:visible[id*='s1']").length; i++) {

if (document.getElementById("s1").offsetWidth < 250) {

var w = document.getElementById("s1");

w.style.width = 250;

}

}

}

The problem is, it is setting width only for first div and rest of the divs its not setting the value 250. I verified using the alert() but its showing value 250 for all the divs. But not rendering in the screen. How to fix this issue?

This issue is coming in all the browsers.

网友答案:

Multiple elements should not have the same ID. Because of this, the getElementByID function only returns the first one with that ID. Change the IDs to classes instead, then use the getElementsByClassName function to select them all and iterate through them.

function SetWidthRPanelAssessments()
{
    var divs = document.getElementsByClassName("s1");
    for (i = 0; i < divs.length; i++)
    {
        if (divs[i].offsetWidth < 250) divs[i].style.width = 250;
    }
}

Or using jQuery to avoid browser conflicts with getElementsByClassName:

function SetWidthRPanelAssessments()
{
    $(".s1").each(function(){
        if ($(this).offsetWidth < 250) $(this).css("width","250");
    });
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: