jquery Uncaught SyntaxError: Illegal break statement

15,910

To exit the anonymous function in the each() use return false. Also note that using a DOMElement to create a jQuery object to then access properties of the DOMElement is entirely redundant. Try this:

$("ul li").each(function() {
    if (this.className === 'active') {
        x = this.className;
        y = this.tagName;
        z = this.id;
        return false;
    } 
});

Also note that your code is effectively only ever selecting the first .active element, therefore the loop is redundant. You can select that element directly and retrieve the necessary properties from it. Try this:

const $li = $('ul li.active:first');
let x = $li.prop('className');
let y = $li[0].tagName;
let z - $li.prop('id');
Share:
15,910
Puni
Author by

Puni

Updated on June 21, 2022

Comments

  • Puni
    Puni almost 2 years

    Uncaught SyntaxError: Illegal break statement

    This is the warning i got when i try to break of the loop. What I want to do break of the loop when the condition is meet.In the example code I have two active class where I want to break out of the loop completely when the first active class is encountered.

    <ul>
        <li id="foo1" class="bar">1</li>
        <li id="foo2" class="bar">2</li>
        <li id="foo3" class="bar">3</li>
        <li id="foo4" class="bar">4</li>
        <li id="foo5" class="active">5</li>
        <li id="foo6" class="bar">6</li>
        <li id="foo7" class="bar">7</li>
        <li id="foo8" class="active">8</li>
    </ul>
    

    js

    $(function(){
        function setup(){
            var x,y,z;
             $("ul li").each(function(){
                 //console.log($(this)[0].className);
                 if($(this)[0].className === 'active'){
                     x = $(this)[0].className;
                     y = $(this)[0].tagName;
                     z = $(this)[0].id;
                     break;
                 } 
             });
            var return_values = {
                class : x,
                tag : y,
                id : z
            }
            return(return_values);
        }
        var data = setup();
        console.log(data.class,data.tag,data.id);
    });
    

    JSFIDDLE here

  • Puni
    Puni almost 9 years
    Ok thanks. I thought return will exit the whole function, my bad I didn't try that.
  • Rory McCrossan
    Rory McCrossan almost 9 years
    No problem, glad to help. For reference, return only applies to the scope of the function which contains it.