Behseini Behseini - 5 months ago 7
jQuery Question

Issue On Selecting Only Elements which has Children

Can you please take a look at this demo and let me know why the code adding

<i class="red"> + </i>
to all
<li>
s under the child
<ul>
. What I would like to do is just adding
+
to
<li>
(s) which contain a new set of
<ul>
but as you can see it is adding to all children



$(function() {
$('li:has(ul)').find('span').append('<i class="red"> + </i>');
});

.red{color:red;}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li><span>Item 1</span></li>
<li><span>Item 2</span>
<ul>
<li><span>Item 2-1</span></li>
<li><span>Item 2-2</span></li>
<li><span>Item 2-3</span></li>
<li><span>Item 2-4</span></li>
</ul>
</li>
<li><span>Item 3</span></li>
<li><span>Item 4</span></li>
</ul>





enter image description here

Answer

Use a descendent > selector:

$(function() {
  $('body > ul > li:has(ul)').find('> span').append('<i class="red"> + </i>');
});
.red {
  color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li><span>Item 1</span></li>
  <li><span>Item 2</span>
    <ul>
      <li><span>Item 2-1</span></li>
      <li><span>Item 2-2</span></li>
      <li><span>Item 2-3</span></li>
      <li><span>Item 2-4</span></li>
    </ul>
  </li>
  <li><span>Item 3</span></li>
  <li><span>Item 4</span></li>
</ul>

Preview

enter image description here