views:

29

answers:

1

I'm trying to select the text from the name attribute of the anchor element of the last Comment div in the Comments div (i.e. comment_3037) How can I select it?

Here's my html:

<div id="Comments">
    <div class="Comment"><!-- last "Comment" element in the div -->
        <a name="comment_3037"></a>
        <a href=""><img src=""></a>
        <div>
            <div class="Stats">Some info goes here</div>
            <div class="Body">Comment goes here.</div>
        </div>
    </div>
</div>
+2  A: 

Corrected Version (dojo.query always returns a nodelist)

This would look something like that:

var nodelist = dojo.query('#Comments > .Comment:last-child > a[name]);'
var value = dojo.attr(nodelist.at(0), 'name');

Explanation: #Comments > .Comment selects all nodes with class Comment inside the node with id Comments. :lastChild reduces this selection to the last child. > a[name] selects all immidiate children of type a with the attribute name. The second line just gets the value from the name attribute of the node.

You should get the correct element with that, but I haven't tested it.

Have a look at the dojo reference, there are tons of useful functions. (I don't work at dojo, I just really like it ;) )

Info

http://docs.dojocampus.org/dojo/query

EDIT

To make sure that you get only the node you want (if you add another link with a name attr), you could add a class "thisisthelinkiwant" (or similar ;) ) to the appropiate link and updating the query to 'Comments .thisisthelinkiwant:last-child'.

You might consider reading about css selectors, as they are quite important with this function.

PvB
thanks a lot! I couldn't get your example to work, but this is how I got it to work: var nameValue = dojo.query('#Comments .Comment:last-child > a[name]').attr('name');
Andrew
Ok, this is interesting, because dojo.query() should return a list of nodes, not a single node... I might have a look at it again...
PvB