-1

This is some code i made up following a course:

$(document).ready(function(){
    $.ajax({
        type: 'GET',
        dataType: 'XML',
        url: 'user_timeline.xml',
        success: processXML
    });

    function processXML(response){
        var status = $(response).find("status");
        for (var i=0; i < status.length; i++){
            var text = $("text",status[i]).text();
            $('#status').append("<p>" + text + "</p>");
        };
    }
});

It works fine, but can someone explain this:

$("text",status[i])

Does it search/select the status array for the key 'text'?

I want to know what i'm doing, not just doing it...

1
  • I would recommend opening up your browser dev tools and set a breakpoint at that line. Then you can step through and understand what each piece does. Commented Sep 18, 2012 at 19:03

1 Answer 1

1

That specific line is looking for a text element inside status[i]. See the jQuery docs on this:

http://api.jquery.com/jQuery/

Selector Context

By default, selectors perform their searches within the DOM starting at the document root. However, an alternate context can be given for the search by using the optional second parameter to the $() function. For example, to do a search within an event handler, the search can be restricted like so:

$('div.foo').click(function() { $('span', this).addClass('bar'); });

When the search for the span selector is restricted to the context of this, only spans within the clicked element will get the additional class.

Internally, selector context is implemented with the .find() method, so $('span', this) is equivalent to $(this).find('span').

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, but do you have a more direct link explaining this syntax?
@Nomistake, check out the link I put in my answer, specifically the section near the top titled Selector Context.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.