unangelic
unangelic

Reputation: 75

Use jQuery to get selected element's hierarchy position/number?

Please bear with me. I'm trying my best to explain what I need, but I'll probably need a few updates to my OP.

I want to get the position of a selected element in the hierarchy. For example, if I have a total of 4 hyperlinks within the entire html document, and I hover over the third link, I want "html > body > a:eq(2)" - 2 signifying the 3rd hyperlink element.

And no, index() doesn't do the trick.

I have tried this code with a little tweaking and get this: "html > body > a", but cannot find a function to return the position.

How do I get the position of the selected element within a hierarchy of similar elements? (I do not even know if that's the right terminology.) Will I need to traverse the DOM and perform a manual match if x==y kinda thing

<a href=#">link1</a> 
<a href=#">link2</a> 
<a href=#">link3</a> 
<a href=#">link4</a>

I will use this code for all kinds of HTML elements, not just hyperlinks.

Upvotes: 1

Views: 1588

Answers (3)

Craig MacGregor
Craig MacGregor

Reputation: 4629

Since you want an action on hover I would suggest a slightly different approach. Instead of finding all the elements to get the index on every hover (which could happen quite often) event I would set the index when the document first loads so you can easily retrieve it when the event fires.

Something like:

$('a').each(function(i, el){            
    $(this).data('index', i); 
    $(this).hover(function(){
        var hoveredIndex = $(this).data('index');
        // Do you action with the index
    });
});

If you don't have much mark up or hovering doesn't happen often this might be overkill. Also if you have a container around the elements the selector/events could be revised.

Upvotes: 0

jfriend00
jfriend00

Reputation: 708056

If you have a given element and want to know what nth link it is in the document, you can do that like this:

function whichLink(el) {
    return $("a").index(el);
}

This form of .index(el) returns which item in the jQuery object matches the passed in element. It searches the jQuery object to find the matching element. Since the jQuery object sorts the elements in document order, this will give you the position in the document of a given link.

If you're trying to do something different, then please clarify your question further.

Upvotes: 1

lucuma
lucuma

Reputation: 18339

Typically you can do this inside an each loop:

$('a').each(function(i) {
  // i has the index so we can do something with it
  var index = i;
  $(this).click(function() {
     $(this).attr('href', index);  // make the href = i for instance
  });
});

Upvotes: 0

Related Questions