0

I'm trying to get the id attr from different onclicks.

Here is the html I have.

<div id="name-1"> 
    <a href="#" class="view">
<div> 

<div id="name-2"> 
    <a href="#" class="view">
<div> 

<p>Name: <span class='name'></span></p>

<script>
$(".view").click(function() {
    var id = $(".view").closest("div").attr("id");
    $('.name').html(id);    
}); 
</script>

When I click the first view I see "name-1" however when I click the second view nothing happens. Also, when I click the second name it shows "name-1". I know this is probably easy to solve but it's friday so I appreciate the help.

2 Answers 2

4

Change

var id = $(".view").closest("div").attr("id");

to

var id = $(this).closest("div").attr("id");

Right now your current code is looking at the first .view on the page rather than the .view whose click event was triggered.

Sign up to request clarification or add additional context in comments.

Comments

1

The reason is you are using the view class selector to get the closest id. So, it looks for the first available view and gets you the id for first DIV.

Consider using $(this) to get the closest id for the clicked element.

$(".view").click(function() {
    var id = $(this).closest("div").attr("id");
}); 

Don't forget to read this article on "jQuery this": http://remysharp.com/2007/04/12/jquerys-this-demystified/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.