Reputation: 4512
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
Upvotes: 1
Views: 246
Reputation: 18078
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);
Upvotes: 0
Reputation: 36531
try this
$('.red-box').has('h2:contains("My Cars")').find('div.block_topic:contains("3")');
$('.red-box').has('h2:contains("My Cars")')
=> gets .red-box containing "My cars".
.find('div.block_topic:contains("3")')
=>finds div.block_topic containing 3
Upvotes: 0
Reputation: 144689
$('.red-box').has('h2:contains(My Cars)').find('div.block_topic').eq(2);
Upvotes: 1