Question

I like to access an anchor (a) element with a specific name in jQuery to obtain its position. I tried the following:

HTML:

<a name="test">An anchor.</a>

JavaScript:

var top = $("a [name=test]").position().top;

Returns empty object.

var top = $("a").position().top;

and

var top = $("[name=test]").position().top;

finds it. How do I write it to get an anchor element with name "test"?

Was it helpful?

Solution

You don't need space after a in your selector:

var top = $("a[name=test]").position().top;

If you put space then it'll find the child elements with name test of any anchor instead.

OTHER TIPS

Remove the space :

var top = $("a[name=test]").position().top;

A space indicates that you're looking for a child element.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top