Reputation: 302
How can I search an element for a text string and hide another? For example: if a div contains the name of John, the div that contains the name of George should be hidden.
<div>John Resig</div>
<div class="test">George Martin</div>
<div>Malcom John Sinclair</div>
<div>J. Ohn</div>
<div>John Resig</div>
<div>George Martin</div>
<div>Malcom John Sinclair</div>
<div>J. Ohn</div>
I have tried:
$(document).ready(function() {
$( "div:contains('John')" )."div:contains('George')".hide();
});
Or shouldn't I use jQuery contains in the first place?
Upvotes: 0
Views: 418
Reputation: 358
I think you should use siblings
instead of next
, because next
won't work if George will be before John
<div>George Martin</div>
<div>John Resig</div>
<div>Malcom John Sinclair</div>
<div>J. Ohn</div>
$(document).ready(function() {
$("div:contains('John')").siblings("div:contains('George')").hide(); // hide all "Georde"
// $("div:contains('John')").siblings("div:contains('George')").first().hide(); // hide only first "Georde"
});
Upvotes: 1
Reputation: 27051
You can do something like this:
$("div:contains(George)").toggle($("div:contains('John')").length)
$(document).ready(function() {
$("div:contains(George)").toggle($("div:contains('John')").length)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>John Resig</div>
<div>George Martin</div>
<div>Malcom John Sinclair</div>
<div>J. Ohn</div>
Upvotes: 0
Reputation: 4462
You are so close!
$( "div:contains('John')" ).next("div:contains('George')").hide();
use Next to find the next element matching.
Source: https://api.jquery.com/next/
Upvotes: 1
Reputation: 30729
You jQuery is incorrect by all means. You need to use :
if($("div:contains('John')").length){
$("div:contains('George')").hide();
}
$(document).ready(function() {
if($("div:contains('John')").length){
$("div:contains('George')").hide();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>John Resig</div>
<div>George Martin</div>
<div>Malcom John Sinclair</div>
<div>J. Ohn</div>
Upvotes: 2