Behseini
Behseini

Reputation: 6330

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

Upvotes: 1

Views: 28

Answers (2)

Karl Doyle
Karl Doyle

Reputation: 642

It is because .find is looking for all span elements that are a descendent of the li element. As mentioned in the description here

The following solution is what you are looking for

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

Which targets just the children of the li element Demo here

Upvotes: 2

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167182

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

Upvotes: 2

Related Questions