April 8, 2012

List of li elements in jquery

Question by Gabriel Żukowski

I don’t know why my code doesn’t work.

$("#example").find('LI A').hasClass("sth").each(function(){alert($(this))});

Firebug says:

$(“#example”).find(‘LI A’).hasClass(“sth”).each is not a function

The problem in this code is each, because if I delete it, it giving me no errors.

I need to pass founded value of “a” element to array.

Answer by gdoron

hasClass function returns boolean not a jQuery object. thus it doesn’t have the each function.

You probably meant this:

$("#example").find('LI A.sth').each(function(){alert($(this))});

Or this (which is better):

$("#example li a.sth").each(function(){alert($(this))});

Read the docs:

.hasClass( className ) Returns: Boolean

Description: Determine whether any of the matched elements are assigned the given class

Answer by Starx

Your application of hasClass is incorrect. It does not return a jQuery Object, but a boolean, so .each() cannot be applied to it.

You have to attach the class to the selector

$("#find").click(function (){
    $("#example").find('a.sth').each(function(){
        $("#test").append($(this));
    });
 });

Demo

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!