how to access the class array with jQuery? Take the second class of an element

Asked

Viewed 648 times

2

I’m listing the icons from a list on console.log() they are displayed, however I want to capture only the second classes of icons in a variable, but I don’t know how to access with jQuery the second classes of the tag <i>. I’m using this code to access the tags <i> who are on the list <li>

clickAtual = $('li.card').children().find('i');

Below the list is displayed, however I want to access the second class of this list as shown below.

exibição da lista no console.log

2 answers

1

Thus:

classeDesejada = $('li.card').children().find('i:eq(0)');

You pass in the :eq() the desired position. See more about the eq-selector in the documentation of JQuery.

  • I tried here but the console continues to print all the classes. I looked at jQuary’s Document '.eq()'.

1


No need to use .children(). The .find() you will already find everything (children, grandchildren, great-grandchildren, great-grandchildren etc.):

$('li.card').find("i")

From there, using the loop .each() you can make a split and take the index [1] (second class) of each one and store in an array. With the mounted array you can convert into string, iterate, do whatever you want:

var clickAtual = $('li.card').find("i");
var array = [];
clickAtual.each(function(i,e){
   var c = e.className.split(" ")[1];
   array.push(c);
});


console.log(array);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
   <li class="card">
      <i class="classe1 classe2 classe3"></i>
      <i class="classe1 classe21 classe3"></i>
      <i class="classe1 classe22 classe3"></i>
      <i class="classe1 classe23 classe3"></i>
   </li>
</ul>

  • Bro, it worked super well here, '.find()' search all the same, thanks.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.