[英]How to select inner most div element using javascript
<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. 我想使用CSS在最里面的div中更改段落标签的颜色。
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 div p { color: red};
is there any other way to select the inner most div and select the paragraph elements to change the color. 还有其他方法可以选择最里面的div并选择段落元素以更改颜色。
JS fiddle JS小提琴
Let me introduce you to CLASS and ID . 让我向您介绍CLASS和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 如果您使用ID,这就是您的代码的样子
EXAMPLE1 (with ID's) 示例1 (带有ID)
EXAMPLE 2 (with Classes) 示例2 (带有类)
HTML 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 CSS
#red
{
color:red;
}
#blue
{
color:blue;
}
#green
{
color:green;
}
Why dont you just assign a class? 您为什么不分配课程?
<div class="test">
<p> Fourth </p>
<p> Fifth </p>
</div>
.test p{
color:red;
}
Please find the solution here 请在这里找到解决方案
http://jsfiddle.net/ramanmandal2/ReAVn/ 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
}
If you are trying to add css only to inner most div child of a div , you can use following code: 如果尝试仅将css添加到div的最里面的div子级,则可以使用以下代码:
div:not(div)
{
color:red;
}
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 的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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.