bohan
bohan

Reputation: 1699

I want to get the first DOM object but not the property of the first object

There are 3 tag a in the HTML Document. As following:

<nav id="navigation">
    <a href="#" tabindex="1" class="active_nav">nav1</a>
    <a href="#" tabindex="2">nav2</a>
    <a href="#"tabindex="3">nav3</a>
</nav>

I use jquery selector expect to get the first <a> like this

alert($("#navigation >a")[0]);

but it shows the href property of the 1st <a> !!!!!

If I replace <a> with <div> , it works.

<nav id="navigation">
    <div >nav1</div>
    <div >nav2</div>
    <div >nav3</div>
</nav>

when alert($("#navigation >div")[0]); it shows the 1st DOM object. I think it very strange. Help me!

Upvotes: 1

Views: 54

Answers (3)

Paul
Paul

Reputation: 141877

That's because the toString of an HTMLAnchorElement just returns the href property.

$("#navigation > a")[0];           // HTMLAnchorElement
$("#navigation >a")[0].href;       // "http://example.com/#"
$("#navigation >a")[0].toString(); // "http://example.com/#"

alert only takes a string as an argument, so toString is automatically called on your Element and you end up seeing the href property.

You should use console.log for debugging, not alert. It is many times more useful.

Upvotes: 1

Ford
Ford

Reputation: 2597

The square braces mean a different thing, it accesses the HTMLElement of the first object in the matched set. What you're looking for is .eq (specifically .eq(0)) and like @Paulpro said, alert forces toString.

Reference: http://api.jquery.com/eq/

Upvotes: 0

Vond Ritz
Vond Ritz

Reputation: 2012

Try these.

alert($("#navigation > a").first().text());

or

alert($("#navigation > a").first().html());

Upvotes: 0

Related Questions