Joe Paul
Joe Paul

Reputation: 71

Merging these two if... else statements

Sorry, I'm new to jQuery. So I have this jQuery code with two if else statement, which I want to merge 'cause I feel it's an unnecessary repetition. They are somewhat different codes, since once is acting on ul#tabs li a and the other on ul.tabs li a. How can I merge them to improve performance? Here is the code:

$(document).ready(function() 
{
    var hash = location.hash;

    $(".tab_content").hide(); //Hide all content

    if ($("ul#tabs li a[href='" + hash + "']").length) 
    { 
        $("ul#tabs li a[href='" + hash + "']")
            .addClass("active")
            .parent()
            .addClass("active"); //Activate tab

        $(hash).show();
    }
    else 
    {
        do stuff
    }  

    if ($("ul.tabs li a[href='" + hash + "']").length) 
    {
        $("ul.tabs li a[href='" + hash + "']")
            .addClass("active")
            .parent()
            .addClass("active"); //Activate tab

        $(hash).show();
    }
    else 
    {
        do stuff
    }  
}); 

How do I merge these two codes?

Upvotes: 0

Views: 126

Answers (2)

SomeShinyObject
SomeShinyObject

Reputation: 7801

You could utilize multiple selectors with a comma:

if ($("ul.tabs li a[href='" + hash + "'], ul#tabs li a[href='" + hash + "'] ").length) {

For your case you could go with the each() method:

var el = $("ul.tabs li a[href='" + hash + "'], ul#tabs li a[href='" + hash + "']");

if(el.length) {
    el.each(function() {
        $(this).addClass("active").parent().addClass("active");
        $(hash).show();
    }); 
} else {
   // do else stuff
}

Upvotes: 2

Jacob Krall
Jacob Krall

Reputation: 28825

The comma operator, ,, is used in CSS and jQuery to specify multiple selectors:

    var sel = $("ul.tabs li a[href='" + hash + "'], ul#tabs li a[href='" + hash + "']");
    if (sel.length) { 
        sel.addClass("active").parent().addClass("active"); //Activate tab
        $(hash).show();
    }
    else {
        do stuff
    }

You can reduce duplication even further:

var sel = $("ul.tabs, ul#tabs").find("li a[href='" + hash + "']");
....

Upvotes: 3

Related Questions