[英]How to find nth p element?
I want to find the 3rd p tag
of each category, based on first p tag's value. 我想根据第一个p标签的值找到每个类别的第三个p tag
。 eg The first p tag value is Tie
, then find the quantity of it. 例如,第一个p标签值是Tie
,然后找到它的数量。
If the html element tree should be formatted in a better way, I am open to it. 如果html元素树的格式应该更好,那么我可以接受。 The html for all ul
is written from code behind at C# to load items from database. 所有ul
的html是从C#后面的代码编写的,以从数据库加载项目。
$("#wel div ").each(function(index, element) {
if ($(this).('p:nth-of-type(1)').html() == "Tie")
{
$(this).('p:nth-of-type(3)').css('background-color','red');
}
}
<div id="fel">Category1
<ul>
<li>
<div >
<p>Shirt</p>
<p>Price:$25</p>
<p>Quantity:20</p> <!--find this?-->
</div>
</li>
<li>
<div>
<p>Tie</p>
<p>Price:$10</p>
<p>Quantity:10</p>
</div>
</li>
<li>
<div>
<p>Trousers</p>
<p>Price:$50</p>
<p>Quantity:5</p>
</div>
</li>
</ul>
</div>
<div id="wel">Category2
<ul>
<li>
<div >
<p>Shirt</p>
<p>Price:$25</p>
<p>Quantity:20</p>
</div>
</li>
<li>
<div>
<p>Tie</p>
<p>Price:$10</p>
<p>Quantity:10</p><!--find this?-->
</div>
</li>
<li>
<div>
<p>Trousers</p>
<p>Price:$50</p>
<p>Quantity:5</p>
</div>
</li>
</ul>
</div>
You can 2 top level elements with different ids fel
and wel
so need to use #wel div, #fel div
to find the category div
elements, then need to use .find() to find the p
你可以用不同的ID 2个顶级元素fel
和wel
因此需要使用#wel div, #fel div
找到类div
元素,那么就需要使用.find()找到p
$("#wel div, #fel div").each(function (index, element) { if ($(this).find('p:nth-of-type(1)').html().trim() == "Tie") { $(this).find('p:nth-of-type(3)').css('background-color', 'red'); } })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div id="fel">Category1 <li> <div> <p>Shirt</p> <p>Price:$25</p> <p>Quantity:20</p> <!--find this?--> </div> </li> <li> <div> <p>Tie</p> <p>Price:$10</p> <p>Quantity:10</p> </div> </li> <li> <div> <p>Trousers</p> <p>Price:$50</p> <p>Quantity:5</p> </div> </li> </div> <div id="wel">Category2 <li> <div> <p>Shirt</p> <p>Price:$25</p> <p>Quantity:20</p> </div> </li> <li> <div> <p>Tie</p> <p>Price:$10</p> <p>Quantity:10</p> <!--find this?--> </div> </li> <li> <div> <p>Trousers</p> <p>Price:$50</p> <p>Quantity:5</p> </div> </li> </div>
You can also do 你也可以
$("#wel div, #fel div ").each(function (index, element) {
var $ps = $(this).find('p');
if ($ps.eq(0).html().trim() == "Tie") {
$ps.eq(2).css('background-color', 'red');
}
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.