Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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');  } 
like image 428
JamesTBennett Avatar asked Aug 03 '10 08:08

JamesTBennett


People also ask

What is the following syntax is used to apply not equal filter on HTML elements using jQuery?

The not() is an inbuilt function in jQuery which is just opposite to the filter() method. This function will return all the element which is not matched with the selected element with the particular “id” or “class”.


1 Answers

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/

like image 58
Felix Kling Avatar answered Sep 28 '22 06:09

Felix Kling