zilcuanu
zilcuanu

Reputation: 3715

select elements by condition using jquery

I am having a ul with li and <i> tag as children. The code is as below

<li class="accordion put">
  <span><i class="fa fa-plus-circle"></i></span><span style="padding-left:5px;font-size: 18px;">Topic-Heading</span>
  <ul class="panel2" style="display: none;">
    <li class="testing"><i class="fa fa-chevron-right"></i> section 1</li>
    <li class="testing"><i class="fa fa-chevron-right"></i> section 2 </li>
    <li class="testing"><i class="fa fa-chevron-right"></i> section 3</li>
    <li class="testing"><i class="fa fa-chevron-right"></i> section 4 </li>
  </ul>
</li>

I have the below jquery code to toggle the class on click on the li as shown below:

$(".put.accordion" ).click(function() {
    $(this).children("ul").toggle("slow");
    $(this).find("i").toggleClass("fa-plus-circle fa-minus-circle");
});

The above code is working fine when I click on the li tag but since I have mentioned find('i') both the i tags are changing. I need to toggle only the i element having the class as fa-plus-circle and to ignore the i with class fa-chevron-right.

Please let me know where I am going wrong.

Upvotes: 2

Views: 1412

Answers (3)

Ngo Tuan
Ngo Tuan

Reputation: 205

You can find with :

find("i[class=fa-plus-circle]")

Detail in : https://www.w3schools.com/cssref/css_selectors.asp. hope to help you

Upvotes: 0

agrm
agrm

Reputation: 3852

If you want a class independent way of selecting the first <i>, you can use .first() to reduce the matched results to the first returned <i> only.

In your case you could replace this line:

$(this).find("i").toggleClass("fa-plus-circle fa-minus-circle");

With this:

$(this).find("i").first().toggleClass("fa-plus-circle fa-minus-circle");

A generic example:

$('body').on('click', function() {
    console.log( $(this).find('i').first().text() )
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Click anywhere to return the contents of the first <code>&lt;i&gt;</code>.</p>

<i class="first">First</i>
<i class="second">Second</i>
<i class="third">Third</i>

Upvotes: 1

S&#233;bastien
S&#233;bastien

Reputation: 12139

You can use the same syntax in find() as with other jQuery selectors. Just specify the class:

$(".put.accordion" ).click(function() {
   $(this).children("ul").toggle("slow");
   $(this).find("i.fa-plus-circle i.fa-minus-circle").toggleClass("fa-plus-circle fa-minus-circle");
});

Upvotes: 0

Related Questions