Find li whose children an element has an empty string
source link: https://www.codesd.com/item/find-li-whose-children-an-element-has-an-empty-string.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Find li whose children an element has an empty string
Example HTML
<li class= "View">
<a><span>Red</span></a>
</li>
<li class= "View">
<a><span>Orange</span></a>
</li>
<li class= "View">
<a><span>Green</span></a>
</li>
<li class= "View NotView">
<a><span>Green not view</span></a>
</li>
<li class= "View">
<a><span></span></a>
</li>
<li class= "View">
<a><span>Brown</span></a>
</li>
I want to select all li tags which has class View and do not have class NotView And span tag under li tag cannot be empty so I need output to be
Red
Orange
Green
Brown
You can use :not()
pseudo-class selector to avoid element with a certain class and then filter out empty element using filter()
method.
console.log(
$('li.View:not(.NotView)').filter(function() {
return $(this).text().trim().length
}).map(function() {
return $(this).text().trim();
}).get()
)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li class="View">
<a><span>Red</span></a>
</li>
<li class="View">
<a><span>Orange</span></a>
</li>
<li class="View">
<a><span>Green</span></a>
</li>
<li class="View NotView">
<a><span>Green not view</span></a>
</li>
<li class="View">
<a><span></span></a>
</li>
<li class="View">
<a><span>Brown</span></a>
</li>
</ul>
With :has()
pseudo-class selector instead of filter()
method.
console.log(
$('li.View:not(.NotView):not(:has(:empty))').map(function() {
return $(this).text().trim();
}).get()
)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li class="View">
<a><span>Red</span></a>
</li>
<li class="View">
<a><span>Orange</span></a>
</li>
<li class="View">
<a><span>Green</span></a>
</li>
<li class="View NotView">
<a><span>Green not view</span></a>
</li>
<li class="View">
<a><span></span></a>
</li>
<li class="View">
<a><span>Brown</span></a>
</li>
</ul>
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK