Selecting DOM elements

Selecting DOM elements of a given type in a document is a simple task, and we can easily do it using standard JavaScript functionality. Nevertheless, jQuery makes it even simpler.

Here is the code to get all the LI elements in the current document, both in plain JavaScript, and using jQuery:
var li = document.getElementsByTagName("li"); // 1
var $li = $("li"); // 2

console.log("li: ", li, li.length);
console.log("$li: ", $li, $li.length);
1. The getElementsByTagName() method returns a NodeList, a structure that is array-ish but does not derive from Array. It sports a property, length, that contains the number of element contained, and lets the user access each of them through the [] operator. An out of bound request is resolved to null.
2. A call to jQuery factory function returns a jQuery object that, for what we care here, is not different from a NodeList object, but it is enriched by extra-information and functionality, that could be useful in more a demanding context.

No comments:

Post a Comment