tags:

views:

28

answers:

2

I have this html page which globally exists of div, section, and ul elements (of course some more, but those are the most common)

Now in my fourth list on the page (e.g. below in bold)


<body>
 <div>
  <header>
   <ul id="firstList">
    <li>
    [..]
  <section>
   <ul id="secondList">
    [..]
  <section>
   <ul id="thirdList">
   [..]
  <section>
   <ul id="fourthList">
    <li><a>Test 1</a></li>
    <li><a>Test 2</a></li>
    <li><a>Test 3</a></li>
   </ul>
  [..]

The thing is that, when someone clicks on a test, i want to loop through the list-items to look the position of the click up in the list (it there are items before or after)

Herefore i have the following


$("a").click(function(event){
 [..]
 var parentEl = $(this).parents('ul').filter(":first").tagName;
 alert($(parentEl).attr("id"));
});

But this gives me firstList as an output. I assume jQuery looks through the document from top down, so the output with filter(:first) (oh and get(0)) as well makes sence i guess.. But how am i going to get the first parent of the clicked link?

If someone click on Test 2 i want to get fourthList as an output (and eventually the position, but that's for later)

A: 

Try this

$("a").click(function(event){
  [..]
  var $parentEl = $(this).closest('ul');
  alert( $parentEl.attr("id") );
});

And to get the position of the link among it's siblings

$("a").click(function(event){
  [..]
  // returns the 0-based index of the `li` among it's sibling `li`s
  var idx = $(this).parent().prevAll().length;
});
BBonifield
Brilliant! Thanks! You really gotta know all the functions haha!
Maurice
A: 

I'm going to leave an answer even though you accepted one because the accepted answer doesn't explain the actual issue.

Your code was correct, except for one thing. You were storing the tagName in a variable, and using that to fetch all <ul> elements on the page. If you would have gotten rid of that, your code would work.

$("a").click(function(event){
   var parentEl = $(this).parents('ul').filter(":first");
   alert( parentEl.attr("id") ); // should alert "fourth"
});

A slightly shorter version would be:

$("a").click(function(event){
   var parentEl = $(this).parents('ul:first');
   alert( parentEl.attr("id") ); // should alert "fourth"
});

The .parents() method will return the elements in the order in which they are found, so :first gives you the first one found.

From the docs:

..the elements are returned in order from the closest parent to the outer ones.

You can also use .closest(), but the outcome will be the same.

Also, in order to get its position from among its siblings, there's a much simpler way using jQuery 1.4 or later. You can just call .index(), as in:

var index = $(this).parent().index();

This gives you the position of the <li> from among its siblings.

patrick dw