0

Is it necessary to use the second line here?

  $("message",xml).each(function(id) {
    message = $("message",xml).get(id);
    msgID = $("msgID",message).text();

Isn't there some kind of 'this' keyword to eliminate the second line?

Thanks!

2 Answers 2

3
$('message', xml).each(function() {
    var msgID = $(this).find('msgID').text();
}  

Assuming this structure:

<root>
    <message>
        <msgID>123</msgID>
    </message>
    <message>
        <msgID>234</msgID>
    </message>
    <message>
        <msgID>345</msgID>
    </message>
</root>
Sign up to request clarification or add additional context in comments.

5 Comments

Can you just write this.find, without using the jQuery symbol and parentheses?
@Michael No, because the this keyword refers to the XML node object (or whatever it's name is), but find() is a jQuery method and it can only be called on jQuery objects.
well, it's a good practice to capture $(this) in a variable. Like var $this = $(this);...
@Reigel I've done some benchmarking and on my machine it takes 0,00021ms to execute $(this). Performance-wise, it's not an issue. jsfiddle.net/aFUKH
hehe I'm not saying it's an issue. :) Just a good practice. artzstudio.com/2009/04/jquery-performance-rules/…
1

When you're in an .each(), this will represent the current item in the iteration.

The .each() also gives you 2 parameters. The first is the current index number of the iteration, and the second is the item in the iteration, same as this.

$("message",xml).each(function( idx, val ) {
    // in here, "this" is the current "message" node in the iteration
    // "i" is the current index in the iteration
    // "val" is the same as "this"
});

When you do $("message",xml), you are looking for "message" nodes that are nested under the nodes at the top of xml. If any were found, the .each() will iterate over them.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.