Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
102
rated 0 times [  104] [ 2]  / answers: 1 / hits: 66067  / 14 Years ago, tue, august 3, 2010, 12:00:00

So I want to get the first <a> tag in this <div>. This is really driving me nuts. Thanks for any help.


HTML


<div id="PGD" class="album" onmouseover="load(this)">
<a class="dl" href="#">DOWNLOAD</a>
</div>

Javascript


function load(dl)
{
var ID = $(dl).attr('id');
var elemnt = $('ID:first').attr('id');
}

More From » jquery

 Answers
57

Non-jQuery: (was not tagged with jQuery before, so I included this)




  • If you want to get the first child element only:



    var element = document.getElementById('PGD').children[0];

  • If you want to get the first anchor element:



    var element = document.getElementById('PGD').getElementsByTagName('a')[0];



With jQuery:



var element = $('#PGD').find('a:first');
// or, to avoid jQuery's pseudo selecors:
// var element = $('#PGD').find('a').first();


and actually your function can just be



function load(dl)
{
var element = $(dl).find('a:first');
}


Update:



As you are using jQuery, I suggest to not attach the click handler in your HTML markup. Do it the jQuery way:



$(function() {
$(#PGD).mouseover(function() {
$(this).find('a:first').attr('display','inline');
alert($(this).find('a:first').attr('display'));
});
});


and your HTML:



<div id=PGD class=album>
<a class=dl href=#>DOWNLOAD</a>
</div>


​See for yourself: http://jsfiddle.net/GWgjB/


[#96037] Saturday, July 31, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
allanw

Total Points: 421
Total Questions: 132
Total Answers: 102

Location: Trinidad and Tobago
Member since Fri, May 8, 2020
4 Years ago
;