Question

I do not understand why this is not working

I have anchors with multiple classes

<div id="left_menu">
<ul>
    <li>
                    <h1>Nobelova</h1>
                    <a class="manned-flight active" href="#manned-flight">View</a>
                </li>
                <li>
                    <h1>Vízia</h1>
                    <a class="frameless-parachute" href="#frameless-parachute">View</a>
                </li>
                <li>
                    <h1>Projekt</h1>
                    <a class="english-channel" href="#english-channel">View</a>
                </li>
                <li>
                    <h1>Lokalita</h1>
                    <a class="about" href="#about">View</a>
                </li>
                <li>
                    <h1>Mapa</h1>
                    <a class="about" href="#about">View</a>
                </li>
            </ul>

I just need to test if some of that anchors has class "active" and no matter if there is manned-flight,parachute-flight,sky-flight class in first place. Why this code not working?

if($("#left_menu ul li a").hasClass('active')){
//do something
} 

this code never get active class anchor when this "active" class is added by another piece of code

if($(document).scrollTop() >= section1Top && $(document).scrollTop() < section2Top){
    $('#left_menu ul li a.manned-flight').addClass('active');
Was it helpful?

Solution

When performing a test like .hasClass() on a selector which returns multiple elements, it will only perform the test on the first element, so $("#left_menu ul li a").hasClass('active') is equivalent to $("#left_menu ul li a").first().hasClass('active'), so it will only ever resolve to true if the first link has the active class.

If all you need is to determine if one (or more) of the links has the active class, just check the length of the returned collection when targeting the active class (working example):

if($("#left_menu ul li a.active").length > 0)
{
    console.log($("#left_menu ul li a.active").length);
}

If you need to know the actual link that has the active class use .each() to iterate over the collection (working example):

$("#left_menu ul li a").each(function()
{
    if($(this).hasClass('active'))
    {
        console.log($(this).attr('href'));
    }
});

OTHER TIPS

Because there is no li tag in your code.

Change to:

$("#left_menu a").hasClass('active')

Try

if($("#left_menu.ul.li.a").hasClass('active')){
//do something
} 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top