开发者

How to get the first inner element?

So I want to get the first <a> tag in this <div&开发者_StackOverflowgt;. 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'); 
}


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/


$("#PGD").children("a:first")

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>


$(ID).find(':first')

See find jQuery command.

$('#PGD').find('a:first')

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/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜