Wednesday, May 27, 2015

Working with HTMLCollections in JavaScript and jQuery

To manipulate HTMLCollections successfully, one must be able to correctly identify and select the kind of object that one is working with. Depending on the command used on an HTMLCollection a DOM element or jQuery object may be returned.  The kind of commands that can be used on such returned elements or objects depends on the nature of that element or object. jQuery methods can only be used on jQuery objects not DOM elements.

Select and Create HTMLCollection

For example to select and create an HTMLCollection from all paragraph elements in an HTML document:

JavaScript 

document.getElementsByTagName("p")

jQuery

$('p')

Access HTMLCollection and Get Item as DOM Element

To return the first element (in the above case paragraph) in an HTMLCollection as a DOM element use one of the following:

JavaScript

document.getElementsByTagName("p")[0]
document.getElementsByTagName("p").item(0) 

jQuery

$('p')[0]
$('p').get(0)

Note the above jQuery commands return the first element as a DOM element.  DOM elements cannot be modified with jQuery methods. For jQuery methods to work they need to operate on jQuery objects. So something such as $('p')[0].text() will not return the expected result.  Use $('p')[0].textContent instead.

Retrieve Item from HTMLCollections as jQuery Object

To return the first element as a jQuery object use one of the following:

$('p').eq(0)
$('p:eq(0)')
 
Since it returns a jQuery object the command $('p').eq(0).text() should work.

Resources

No comments:

Post a Comment