Chris Sealey
Chris Sealey

Reputation: 68

Is it possible to re-call a successful jQuery selector?

Let's say I have a set of selectors being passed in and then if one of them is successful, I want to re-check for that selector again but underneath a top-level element and then run an event on that if found. So...

$('element1, element2, element3').click(function() {
    $('#header' + successfulElement).addClass('active');
    });

Then, if the user hits any one of those elements (there could be multiple throughout the document) we check to see if an element with the same selector is underneath #header.

Does that make sense? It sounds complicated, but I wouldn't be surprised if I'm missing something fundamental here.

Thanks in advance.

Upvotes: 2

Views: 225

Answers (3)

Kris
Kris

Reputation: 1

Can you side step the issue entirely by giving the elements in question some kind of commonality (eg using a shared data- attribute) then doing the below?

$("selector1, selector2, selector3").bind("click", activate);

function activate(e){
    $(".active").removeClass("active");
    $("[data-id='" + $(this).attr("data-id") + "']",
        $("header")).addClass("active").trigger("some event");
}

Upvotes: 0

casablanca
casablanca

Reputation: 70721

There isn't a generic way to find out which part of a selector matched a given element, but if your selectors have a specific form, you could exploit certain properties. For example, if each elementN is a HTML tag, you could use this.tagName to recover the matched tag:

$('element1, element2, element3').click(function() {
  $('#header ' + this.tagName).addClass('active');
});

Similarly, you could use this.className to get the class name(s) of the clicked element.


Update: Since your selectors are quite complex, the only way out might be to bind individual handlers for each sub-selector. You can automatically generate these handlers like this:

function bindClick(selector) {
  $(selector).click(function() {
    $('#header ' + selector).addClass('active');
  });
}

var selectors = [ 'a[href*="/el1"]', 'a[href*="/el2"]', 'a[href*="/el3"]' ];
for (var i = 0; i < selectors.length; i++)
  bindClick(selectors[i]);

Upvotes: 1

Andy E
Andy E

Reputation: 344783

Use closest():

$('element1, element2, element3').click(function() {
    var $this = $(this);

    if ($this.closest("#header").length)
        $this.addClass('active');
});

You can also use parents(), but closest() does the same job except it stops when it reaches a matching element (so it performs better).

Upvotes: 3

Related Questions