Go through jquery inputs and check if you have a certain class in input

Asked

Viewed 3,345 times

1

I’m picking up the inputs with the code var itensTabelaPresentation = ('#tabelaPresentarion > li'); and would like to walk through them and go checking if they have certain class, how do I accomplish this in a foreach?

<ul class="nav nav-tabs" id="tabelaPresentarion">
	<li role="presentation" id="tabGeral" class="active"><a href="#">Geral</a></li>
	<li role="presentation" id="tabAuditoria" ><a href="#">Audiroria</a></li>
</ul>

<script>
	jQuery(document).ready(function () {

		var tabGeral = $('#tabGeral');
		var tabAuditoria = $('#tabAuditoria');

		var painelGeral = $('#painelGeral');
		var painelAuditoria = $('#painelAuditoria');

		var itensTabelaPresentation = ('#tabelaPresentarion > li');
		
		tabGeral.click(function () {
			painelGeral.show();
			painelAuditoria.hide();

			for (var i = 0; i <= itensTabelaPresentation.length; i++) {
				
			}

		});

		tabAuditoria.click(function () {
			painelGeral.hide();
			painelAuditoria.show();
		});
		
	});
</script>

  • What input are you talking about?

  • I’m getting the list actually, ul > li .. I’ll edit

3 answers

4

Just use the .hasClass() for that reason.

$("#tabelaPresentarion > li").each(function(index) {
  if ($(this).hasClass('active'))
    console.log("O elemento " + index + ": " + $(this).text() + " está ativo.");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="nav nav-tabs" id="tabelaPresentarion">
  <li role="presentation" id="tabGeral" class="active"><a href="#">Geral</a></li>
  <li role="presentation" id="tabAuditoria"><a href="#">Audiroria</a></li>
</ul>

3

As you already have the list of elements you will use to filter the class, var itensTabelaPresentation = ('#tabelaPresentarion > li');, just use the filter method:

var soOsComClasse = itensTabelaPresentation.filter('.suaClasse');

If you need to go through all the same items, just use what you said, each(), beyond the method hasClass()

itensTabelaPresentation.each(function(index) {
  console.log('elemento ' + index + ' tem classe? ' + $(this).hasClass('suaClasse'));
});

More information:

1


You can do so with Jquery:

$('.nav.nav-tabs li').each(function(){
    if($(this).attr('class') == "active"){
        alert("Achei a class!");
    } else {
        alert("A class não está aqui!");
    }
}); 

NOTE: In place of active by the class you want to find.

  • That’s just what I needed.

  • 1

    If there is more than one class in the element, it will not work.

  • But it will not have, because it only active class. An element will only have. But if you have it, it will not work.

  • 4

    just change the attr('class') == "active" for hasClass('active') that everything gets right

Browser other questions tagged

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