My html:
<div class="red-box">
<h2>
<a href="#">My Cars</a>
</h2>
<div class="block_left layout2">
<div class="part1">
<div class="gallery_block">
<div class="block_topic">1</div>
<div class="block_topic">2</div>
<div class="block_topic">3</div>
</div>
</div>
</div>
<div class="red-box">
<h2>
<a href="#">My Bikes</a>
</h2>
<div class="block_left layout2">
<div class="part1">
<div class="gallery_block">
<div class="block_topic">1</div>
<div class="block_topic">2</div>
<div class="block_topic">3</div>
</div>
</div>
</div>
</div>....
There are a lot of "red-box" divs with different titles in <h2><a href="">TITLE</a></h2>
like in example above. And I need to select and change only one - "red-box" -> "block_left" -> "part1" -> "gallery_block" -> "block_topic" which contains "3" and do it only in single "red-box" which got <h2><a href="">My Cars</a></h2>
So, I am doing following:
if ($(".red-box").children("h2").children("a").children("span:contains('My Cars')").length > 0)
{
// it finds the "red-box" which i need but how to select
// <div class="block_topic">3</div> in the "red-box" whose href has "My Cars"?
}
Thanks
$('.red-box').has('h2:contains(My Cars)').find('div.block_topic').eq(2);
If I understand correctly, you don't need an if()
expression, just an appropriately phrased jQuery selection expression.
Also, particularly if the expression is to be generalized, you should avoid :contains
, which is indiscriminate, in that it will find elements with embedded substrings matching the string of interest.
To select elements with exactly matching text, you can use .filter()
, as follows :
$(".red-box h2 a").filter(function() {
return $(this).text() === 'My Cars';
}).closest(".red-box").find(".block_topic").filter(function() {
return $(this).text() === '3';
});
or, if you want a .block_topic
of known index :
$(".red-box h2 a").filter(function() {
return $(this).text() === 'My Cars';
}).closest(".red-box").find(".block_topic").eq(2);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.