Is this code valid/correct
var items = $(".items"); // when would items be properly populated, at dom.ready()??
var itemsHrefs = []; // direct JS code
prepareItemsList(); **// direct JS code**
**// could be the case that items array is not populated yet ???**
function prepareItemsList() {
for ( var i = 0; i < items.length; i++ ) {
var plElement = items.eq(i);
itemsHrefs.push (plElement.attr('href'));
}
}
Questions:
- When would items variable be properly created. I assume dom.ready()??
- Should I put execution of prepareItemsList() inside a document.ready handler to be correct?
NOTE: When I tried doing 2. above, I ran into different issues
You need to put the code that works with the DOM in a
$(document).ready()callback. If you try to work with the DOM before it’s ready, your code will not work properly (or at all).It’s sometimes confusing to keep only a portion of the code in the callback, so I usually just wrap everything jQuery-related in it: