Search code examples
javascriptjqueryhtmlinnerhtml

What kind of object does a jQuery selector return?


I am trying to get the html of "li" elements and alert them as a string.

HTML:

<ul>
    <li>lorem ipsum dolor <span>sit</span> amet 1</li>
    <li>lorem ipsum dolor <span>sit</span> amet 2</li>
    <li>lorem ipsum dolor <span>sit</span> amet 3</li>
    <li>lorem ipsum dolor <span>sit</span> amet 4</li>
    <li>lorem ipsum dolor <span>sit</span> amet 5</li>
    <li>lorem ipsum dolor <span>sit</span> amet 6</li>
</ul>

<p id="greeting">Hello <strong>World</strong>!</p>

Javascript:

$(document).ready(function(e){
    var list =  $("li");
    var greeting = $("#greeting");
    var content ="";
    for(var i=0, len = list.length; i<len; i++) {
        content += $(list[i]).html();   
        //why do I have to use the $ here instead of just doing list[i].html()

      //content += list[i].html(); why does this not work?
    }
    alert(content);
    alert(greeting.html());  //why does this work without the $ ?
});

I have done some research and understood that jQuery selectors return DOM elements wrapped in jQuery objects so that we can apply jQuery methods on it but why does the line greeting.html() work fine without the $?

TypeError: list[i].html is not a function

why do I get this error when I do list[i].html instead of $(list[i]).html()?

Here is the fiddle.


Solution

  • jQuery selections return a jQuery selection set (a "jQuery object"). That object is also an "array like" object meaning you can access the selection through indexer notation like in your example.

    The elements in the selection set are dom elements and not jQuery selection sets themselves. If you want to convert a DOM element to a jQuery selection set you need to wrap it in $(yourElement).

    var jQ = $("div"); // get all divs
    jQ[0]; // the first div, a DOMElement
    $(jQ[0]); // a selection containing the first div of the old selection
    jQ.eq(0); // convenience for the above. 
    

    The reason the API acts this way is for efficiency, if you selected 10000 divs, creating 10000 new objects is wasteful.