2

Here is small fragment to serve as example:

<div id="parentDiv">
    <div>child1</div>
    <div>child2</div>
</div>

With CSS I can do this:

  div#parentDiv { position: absolute; }
  div#parentDiv>div { position: relative; }

How to do same styling with javascript?

4

3 回答 3

5

试试这个:(只有子元素,而不是所有嵌套元素

var pDiv = document.getElementById('parentDiv');
var cDiv = pDiv.children;
for (var i = 0; i < cDiv.length; i++) {
    if (cDiv[i].tagName == "DIV") {   //or use toUpperCase()
        cDiv[i].style.color = 'red';  //do styling here
    }
}

工作小提琴

不是最好的,但您可以参考以下内容:(只是为了获得更多知识

Node.prototype.childrens = function(cName,prop,val){   
    //var nodeList = [];
    var cDiv = this.children;
    for (var i = 0; i < cDiv.length; i++) {
        var div = cDiv[i];
        if (div.tagName == cName.toUpperCase()) {
            div.style[prop] = val;
            //nodeList.push(div);
        }
    }
   // return nodeList;
}

var pDiv = document.getElementById('parentDiv');
pDiv.childrens('div','color','red');
于 2013-07-09T05:17:37.443 回答
2

尝试这个

    var parentDiv1 = document.getElementById('parentDiv');
    var childDiv = parentDiv1.getElementsByTagName('div');
    parentDiv.style.position = "absolute";
    for (var i = 0; i < childDiv.length; i++) {
        childDiv[i].style.position = "relative";
    }
于 2013-07-09T04:56:45.820 回答
-1

您可以使用以下内容:

document.getElementById('parentDiv').childNodes[0].style.position = "relative";
document.getElementById('parentDiv').style.position = "absolute";
于 2013-07-09T05:13:18.893 回答