Arash
Arash

Reputation: 3688

Get the value of div that a href is linked to with jquery

I want to get the div id that a href is linked to when user click on, with jQuery.

How can I achieve this?

<a href="#tips">Visit the Useful Tips Section</a>
<div id="2"> <a id="tips">Useful Tips Section</a></div> 

Upvotes: 0

Views: 92

Answers (6)

Jack
Jack

Reputation: 1941

Give this a try.

$("a#tips").click(function(){
    $(this).parent();
}

Upvotes: 0

Alex Shilman
Alex Shilman

Reputation: 1547

Try this:

$('a[href]').on('click', function(e){
  e.preventDefault();
  var id = $(this).attr('href');
  console.log($(id).html());
});

JSBIN DEMO

Upvotes: 0

John S
John S

Reputation: 21482

The code below attaches an on-click handler to the first anchor element (i.e., the one with the href). It then gets the id of the <div> that is the parent of the other anchor element..

$('a[href]').click(function(e) {
    e.preventDefault();
    var $thisAnchor = $(this);
    var $otherAnchor = $($(this).attr('href'));
    var $div = $otherAnchor.parent();
    var divId = $div.attr('id');
});

Of course, you could shorten this up, but I put in the intermediate variables to show the steps.

Upvotes: 1

Marko Radosevic
Marko Radosevic

Reputation: 150

Give a try

$("#tips").click(function(){
   $(this).parent().attr("id");
 });

Upvotes: 0

Raunak Kathuria
Raunak Kathuria

Reputation: 3225

HTML

Add class to the link to be clicked

<a class='someclass' href="#tips">Visit the Useful Tips Section</a>
<div id="2"> <a id="tips">Useful Tips Section</a></div> 

JS

Attach event to the link so that on click of it you can get div id with this

$(function () {
    $('.someclass').click(function () {
        $(this).attr('href')).parent(); // gets you the div that you require
        $(this).attr('href')).parent().attr('id') // gives you div id that a is linked to
        console.log($($(this).attr('href')).parent().attr('id')); // print div id 2
    });
});

Check http://jsfiddle.net/raunakkathuria/75yut/

Upvotes: 0

Vickel
Vickel

Reputation: 7997

if your script is similar to this:

    <div id="foo">
    <img id="my_img" src="/somewhere_on_my_server/one_img.jpg">
    </div>

you can get the div's id like this

    $(function() {
        $('img').click(function(e){
            alert( $(this).parent('div').attr('id'))
        })
    });

note in stead of parent() you can also use closest(). both go up the tree

Upvotes: 0

Related Questions