Tutorial :How to get the first inner element?


So I Want to get the first 'a' tag in this div. This is really driving me nuts. thanks for any help.

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


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


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');   }   


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/



This will give you the first child "a" tag, but not the descendents. E.g.

     <div id="log">          <p><a href="foo">Foo</a></p>          <a href="hello">Hello</a>          <a href="how">Hello</a>       </div>  

Will give you : <a href="hello">Hello</a>



See find jQuery command.


Actualy I've not understanding problem, so I'm trying correct your function, to make it clear for you:

function load(dl)  {      // var ID = $(dl).attr('id');  // var elemnt = $('ID:first').attr('id'); // Here is error-mast be like $(ID+':first')     var ID = $(dl).attr('id');   var elemnt = $(ID).find('*:first').attr('id');     }   

I supose dl that is $('#PGD'). But child element A have not attribute id, what are you trying to find?

Also See: http://api.jquery.com/category/selectors/

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »