javascript 将 CSS 样式应用于子节点

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17540153/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 08:42:15  来源:igfitidea点击:

Apply CSS style to child nodes

javascripthtmlcss

提问by user

Here is small fragment to serve as example:

这是作为示例的小片段:

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

With CSS I can do this:

使用 CSS 我可以做到这一点:

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

How to do same styling with javascript?

如何使用 javascript 做相同的样式?

回答by Mr_Green

Try this: (to just have only child elements, not all nested elements)

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

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

Working Fiddle

工作小提琴

Not the best one, but you can refer the below: (just for some more knowledge)

不是最好的,但你可以参考以下:(只是为了更多的知识

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');

回答by sangram parmar

try this

试试这个

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

回答by Roy M J

You can use the following :

您可以使用以下内容:

document.getElementById('parentDiv').childNodes[0].style.position = "relative";
document.getElementById('parentDiv').style.position = "absolute";