Need help with jQuery conditional that removes container element based on matched text
here is my markup:
<div>
<h3>Title</h3>
<ul class="eventslist">
<li>This event would be discarded</li>
<ul>
<li>...</li>
<li>...</li>
</ul>
</li>
</ul>
</div>
<div>
<h3>Title</h3>
<ul class="eventslist">
<li>Earnings - This event would be included</li>
<ul>
<li>...</li>
<li>...</li>
</ul>
</li>
</ul>
</div>
I need help writing a conditional that would go through each UL class="eventslist" on the page, and check that the first LI under UL class="eventslist" contains the word "Earnings" (it can be anywhere in the text, and capitilization should be ignored). If it doesn't, the entire DIV wrapped around the UL should be removed along with everything inside it.
Any help 开发者_高级运维is greatly appreciated!
This jQuery would do what you want:
$(document).ready(function(){
$(".eventslist").filter(function(){
var text = $(this).children("li:first").text();
return !/earnings/i.test( text );
}).closest("div").remove();
});
jsFiddle Example: http://jsfiddle.net/dGKMj/2/
$('ul.eventslist').filter(function () {
return !$(this).find('li:first').text().match(/earnings/i);
}).parent().remove();
jsFiddle Demo
Explanation:
- Runs
.filter()
on the.eventslist
lists, and keeps only those that don't haveeanings
somewhere in the firstli
. - Removes the parent (basically the
div
) of these lists. Instead ofparent()
, you can also useclosest('div')
if the markup could change. The most bulletproof would be to give a class to the parentdiv
, and then useclosest('div.container')
.
While the above answers work, I prefer the simplicity of jQuery selectors.
$('ul.eventslist > li:first-child').not(":contains('Earnings'), :contains('earnings')").closest('div').remove();
I think that this is much easier to read and update later. <-- This is my opinion
http://jsfiddle.net/natedavisolds/QFbD2/3/
精彩评论