Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery Uncaught SyntaxError: Illegal break statement [duplicate]

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

like image 286
Puni Avatar asked Jul 28 '15 10:07

Puni


1 Answers

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');
like image 155
Rory McCrossan Avatar answered Oct 05 '22 21:10

Rory McCrossan