Reputation: 4155
I need to select a div (with a class of data) from my page, where one child has a particular value (Test1), and another child has another value (User1);
For instance, I want to select div.data
in this example (Note User1 in div.user
)
<div class="data">
<div>
<div class="details">
Test1
</div>
<div class="user">User1</div>
</div>
</div>
But not this (Note User2 in div.user
):
<div class="data">
<div>
<div class="details">Test1</div>
<div class="user">User2</div>
</div>
</div>
I tried to write a query using :has
, but It either selects both divs, or neither.
$("div.data:has(div.details:contains('Test1'), div.user.contains('User1'))")
How would I write a query to get div.data
in this situation?
Clarification: I wasn't originally clear, but I need to select div.data
When the user div contains "User1" and the details div contains the value "Test1". i.e. Both conditions must be true for div.data
to be selected.
Upvotes: 0
Views: 107
Reputation: 388316
I don't think contains is the best fit for the use case, still try
$('div.data:has(div.details:contains("Test1")):not(:has(.user:contains("User2")))').css('color', 'red')
Demo: Fiddle
$('div.data').filter(function () {
var $this = $(this);
return $.trim($this.find('.details').text()) == 'Test1' && $.trim($this.find('.user').text()) != 'User2'
}).css('color', 'red')
Demo: Fiddle
Upvotes: 2
Reputation: 35321
You should try considering adding classes to your data, so that way you can actually select data that you need.
If you still want to approach this way, best to do it with this:
$('.data').each(function(){
var thisData = $(this);
// Uncomment if you want to find by specific siblings
if($('.user:contains(\'User1\')', thisData).length)
//if($('.details .details', thisData).length)
{
// Do whatever as you like
thisData.css('background', 'green');
}
});
Upvotes: 0
Reputation: 28397
Try this:
$(".data").find("div.user:contains('User1')").parents("div.data")
Demo: http://jsfiddle.net/abhitalks/LvJ7Z/1/
Your requirement is to only select the div
s which are having a class user
(descendents of div
with the class data
) which contain the text "User1". Remember, contains
is case-sensitive.
Upvotes: 0