Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performing the same operation on multiple selectors, elegantly?

On the project I'm working on, I've been writing a little JavaScript object. One of its behaviors involve removing any children in a series of classes, as such:

function Foo () {
    var $a = $('.a'),
        $b = $('.b'),
        // ...etc...
        $n = $('.n');

    $a.remove();
    $b.remove();
    // ...etc again...
    $n.remove();
}

While there are some ways to revise this to be more easily maintainable (putting the selectors into a single array springs instantly to mind), I'm wondering if there's any elegant way to perform the .remove() operation on a series of selectors, as such:

function FooPrime() {
    var selectors = [
        '.a',
        '.b',
        // ...
        '.n'
    ];

    // Perform remove on all given selectors?
    $(selectors).remove();
}

Thus, Question: What are some ways I could perform a single jQuery operation on a number of selectors?

EDIT: here is a JSFiddle to show a cut-down version of the problem context.

like image 356
Andrew Gray Avatar asked Mar 23 '23 18:03

Andrew Gray


2 Answers

You can separate the selectors with commas:

 $(selectors.join(',')).remove();

The comma has that purpose in straight ordinary CSS selector syntax.

like image 96
Pointy Avatar answered Apr 25 '23 16:04

Pointy


Thanks for showing your DOM, you should avoid making big lists of classes to select when you can add multiple classes to elements and create a specific class for the elements you want to target... or target via association to other elements. This would be a more clean and efficient way to do it.


By association

Basically for the selector I just have this:

$("#test-callout").find("div").not(".callout-main").remove();

Fiddle

This assumes that you do not have any other div's besides .callout-main and the target div in test-callout. If you do you can modify the selector chain a bit to compensate.


By adding another class

Your arrow creation code was like this:

function calculateArrow() {
    var arrowClass;
    if(pub.isLeft) {
        arrowClass = 'callout-arrow-left';   
    } else {
        arrowClass = 'callout-arrow-right';
    }

    pub.$callout.append('<div class="' + arrowClass + '"></div>');
}

Modify it to be like this:

function calculateArrow() {
    $arrow = $("<div>")
    .addClass("callout-arrow")
    .addClass(pub.isLeft ? "callout-arrow-left" : "callout-arrow-right");        
    pub.$callout.append($arrow);
}

Then your selector can be simply:

$("#test-callout").find(".callout-arrow").remove();

Fiddle


If you are interested in a complete refactor - I reduced your CalloutObject from 53 to 17 lines and it still works the same.

Fiddle

like image 24
Dallas Avatar answered Apr 25 '23 15:04

Dallas