Reputation: 235
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?
Upvotes: 5
Views: 31932
Reputation: 41832
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');
Upvotes: 8
Reputation: 8726
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";
}
Upvotes: 3
Reputation: 6938
You can use the following :
document.getElementById('parentDiv').childNodes[0].style.position = "relative";
document.getElementById('parentDiv').style.position = "absolute";
Upvotes: -1