Reputation: 1
<body>
<div>
<p>First</p>
<div>
<p>Second</p>
<div>
<p>Third</p>
<div>
<p>Fourth</p>
<p>Fifth</p>
</div>
</div>
</div>
</div>
</body>
I want to change color of the paragraph tags in the inner most div using css.
Ex: Fourth and Fifth should be red and First should be green, Second and Third should be blue
i used
div div div p
{
color:red;
}
But if again another outer div is added again we need to re write it as
div div div div p { color: red};
is there any other way to select the inner most div and select the paragraph elements to change the color.
JS fiddle
Upvotes: 0
Views: 730
Reputation: 276
Please find the solution here
http://jsfiddle.net/ramanmandal2/ReAVn/
var element;
length=document.getElementsByTagName('div').length;
for(i=0;i<length;i++){
element=document.getElementsByTagName('div')[i];
hasDivChild=false;
for(j=0;j<element.childNodes.length;j++){
if(element.childNodes[j].nodeName=="DIV") hasDivChild=true;
}
if(!hasDivChild) element.style.border="1px solid red"; //Bordering red to the innermost div tag
}
Upvotes: 1
Reputation: 2437
var s = "#outerdiv";
while($(s + " >div ").size() > 0)
s += " > div";
$(s).css("color", "#FF0000");
OR
$('#outerdiv div:last').css({color: "red"});
OR
$('body div:last').css({color: "red"});
HTMl
<body id="outerdiv">
<div>
<p> First </p>
<div>
<p> Second </p>
<div>
<p> Third </p>
<div>
<p> Fourth </p>
<p> Fifth </p>
</div>
</div>
</div>
</div>
</body>
Upvotes: 0
Reputation: 3059
Let me introduce you to CLASS and ID. This is how we can distinguish the same elements within a page.
This is how your code will be like if you use ID's
EXAMPLE1 (with ID's)
EXAMPLE 2 (with Classes)
HTML
<div id="green">
<p> First </p>
<div id="blue">
<p> Second </p>
<div>
<p> Third </p>
<div id="red">
<p> Fourth </p>
<p> Fifth </p>
</div>
</div>
</div>
</div>
CSS
#red
{
color:red;
}
#blue
{
color:blue;
}
#green
{
color:green;
}
Upvotes: 2
Reputation: 360
If you are trying to add css only to inner most div child of a div , you can use following code:
div:not(div)
{
color:red;
}
Upvotes: 0
Reputation: 2415
Why dont you just assign a class?
<div class="test">
<p> Fourth </p>
<p> Fifth </p>
</div>
.test p{
color:red;
}
Upvotes: 1