user
user

Reputation: 235

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:

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

How to do same styling with javascript?

Upvotes: 5

Views: 31932

Answers (3)

Mr_Green
Mr_Green

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

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

Upvotes: 8

sangram parmar
sangram parmar

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

Roy M J
Roy M J

Reputation: 6938

You can use the following :

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

Upvotes: -1

Related Questions