0

How would I obtain a selector that would uniquely reference the present targeted DOM element (i.e. this) inside an iteration of a jQuery each loop? So say the selector was #abc, .xyz and the source was:

    <body>
        <div id="abc">1</div>
        <div class="xyz">2</div>
        <div class="xyz">3</div>
        <div class="xyz">4</div>
    </body>

Ideally I'm looking for something like this:

$('#abc, .xyz').each(function() {
    /*
       iteration1 = '#abc';
       iteration2 = '.xyz:eq(0)';
       iteration3 = '.xyz:eq(1)';
       iteration4 = '.xyz:eq(2)';
    */
});

I know the .selector property was removed, but actually that wouldn't have even helped, I'm after a specific selector that would only match "this" iteration of the each().

Why? ...you may ask

I'm trying to load in parts of a new page via Ajax, then only replace certain parts of the current page with the loaded data. I'd like it if I could completely parameterise what is to be ajax-replaced on the current page (possibly in quite a few different places). Hence I wanted a way to loop through multiple possible matches in the loaded data, then replace those specific parts on the current page.

So I can each() loop over a selector through the ajax loaded data, but I don't then have a selector to target each iteration's data onto the current page.

Backtracking, I could rely on IDs, split() the selector string by the commas, and loop over those IDs, but being able to use classes, tags, or other non-unique selectors would be even more flexible!

Francis Booth
  • 676
  • 6
  • 11

1 Answers1

0

If I understand your question correctly, you could use a jQuery extension (like the one listed here) when looping through you .each function.

JSFiddle Demo

$(function () {
    var selectors = [];
    $('#abc, .xyz').each(function () {
        var uniqueSelectorForThis = $(this).getPath();
        selectors.push(uniqueSelectorForThis);
    });

    // Will log this based on your HTML:
    // ["html>body>div", "html>body>div:nth-child(2)", "html>body>div:nth-child(3)", "html>body>div:nth-child(4)"]    
    console.log(selectors);
});
Community
  • 1
  • 1
GFoley83
  • 3,439
  • 2
  • 33
  • 46