1

This might be a duplicate question, however I did search and I got so many different answers that I don't know which to use or how to do this.

<? if(isset($content)) { $i = 1; foreach($content as $item) { echo "<li><a href='#' name='" . $item['id'] . "'>" . $item['title'] . "</a></li>"; $i++; } } ?> 

I've added a function to these links with jQuery to handle an ajax call. I select the links as follows:

 $("#tips_list ul li a").click(function(e) { //... } 

However, this doesn't make a lot of sense because now you have to click on the actual text instead of the list item. So I figured I'd re-structure my HTML so the anchor tag wraps around the li tag.

 `<a href="#" name=""><li>foo</li></a>` 

I then changed my jQuery code accordingly:

 $("#tips_list ul a li").click(function(e) { //... } 

However, now, when I click.. it grabs the list item tag as $(this); which means I can't really grab the name attribute from the anchor tag. So! What I need to do is to grab the name attribute from the parent anchor tag. And I honestly have no clue what the easiest way to do this is. I'm not that experienced with jQuery.

Thanks a lot for helping me!

2
  • $(this).parent() doesn't work? You should also consider updating your css to handle your LI's better. Commented May 11, 2011 at 7:38
  • Don't put an a around a li, it is not valid. Commented May 11, 2011 at 7:45

3 Answers 3

3

Keep the old markup. The later one is quite cranky and use the following script.

$("#tips_list ul li").click(function(e) { var name = $(this).children("a").attr("name"); alert(name); } 
Sign up to request clarification or add additional context in comments.

Comments

1

How about going back to the original method, and set #tips_list ul li a {display:block} in your CSS? That should make the a expand and take up the whole li, making the whole li seem clickable. Your original code should then work fine.

1 Comment

Okay, apparently I was making this too hard on myself and there was a much easier non-jQ way. Thanks a bunch!
1

To get the parent of an element you just need to use $(this).parent() So I would do this: $(this).parent('a').attr('name');

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.