[英]Apply CSS style to child nodes
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做相同的样式?
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
}
}
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');
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";
}
You can use the following : 您可以使用以下内容:
document.getElementById('parentDiv').childNodes[0].style.position = "relative";
document.getElementById('parentDiv').style.position = "absolute";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.