Week 11 Video 11.5 jQuery.each() vs jQuery().each()

by Lucille Kenney

HTML

<p>This is my first paragraph</p>
<p>This is my second paragraph</p>
<p>This is my third paragraph</p>
<p>This is my fourth paragraph</p>
<p>This is my fifth paragraph</p>
<p>This is my sixth paragraph</p>
<p><b>Output</b></p>
<div id="output"></div>

CSS

#output{
    border: 1px solid black;
    padding: 5px;
}

JavaScript

var paras = document.getElementsByTagName("P");
// NodeList can be accessed by [0]
$('#output').append(paras[0]);

// But you can't do this - paras isn't an array, it's a NodeList
/*
paras.forEach(function(i){
   $('#output').append(i);
});
*/

// jQuery Utility function $.each() iterates over objects of any kind
$.each(paras,function(i, v){
    $('#output').append(i + ":" + v.innerHTML + "<br>");//v.innerHTML
});

//jQuery Utility method
//pass in an object literal
$.each({name:"Simon",profession: "cat",},function(i, v){
    $('#output').append(i + ":" + v + "<br>");//v.innerHTML
});


// jQuery().each() selector function iterates over jQuery objects,


//jQuery DOM method
//  usually one returned from a selector.  
$('p').each(function(i, v){
    // v is the HTML element, not a jquery emelent - remember what the selector returns
    $('#output').append(i + ":" + v + "<br>");//v.innerHTML 
});//returns html DOM object

$('p').each(function(i, v){
    // v is the HTML element, not a jquery emelent - remember what the selector returns
    $('#output').append(i + ":" + $(v).html() + "<br>");//v.innerHTML  ... make a jQuery object out of html DOM object
});//returns jquery object