Learn AspNet Learn AspNet - 2 months ago 9
HTML Question

Find li whose children a element has 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

Answer

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>