.contents()S2C Home « Traversal « .contents()

All children retrieval.

Description

The .contents() method is used to retrieve the children of each element within the matched set, including text and comment nodes.

We can also use the .contents() method to get the content document of an iframe, if it is on the same domain as the page we are using it in.

As of jQuery 3.2 .contents() returns the contents of template elements as well.

  • Use the .children() method instead if you don't want text or comment nodes retrieved.

Syntax

Signature Description
.contents()Retrieve the children of each element within the matched set, including text and comment nodes.

Parameters

None.

Return

A jQuery object either containing the elements matched or empty.

Dom Types and Values

We can test the node type by using the nodeType property of each element. The table below gives the names of each node type and their value.


Dom Type Value Dom Type Value
ELEMENT_NODE1ATTRIBUTE_NODE2
TEXT_NODE3CDATA_SECTION_NODE4
ENTITY_REFERENCE_NODE5ENTITY_NODE6
PROCESSING_INSTRUCTION_NODE7COMMENT_NODE8
DOCUMENT_NODE9DOCUMENT_TYPE_NODE10
DOCUMENT_FRAGMENT_NODE11NOTATION_NODE12

.contents() ExamplesTop

Retrieve the children of each element within the matched set, including text and comment nodes.

In the example below we select all 'a' elements on the page. We then further filter to find non ELEMENT_NODE children. We then get the parent of each element in the matched set and turn the background colour to orange.


$(function(){
  $('#btn14').on('click', function() {
    $('a').contents()
          .filter(function(){ 
            return this.nodeType != 1; // Any node type apart from ELEMENT_NODE 
          })
          .parent()
          .css('backgroundColor', 'orange');
  });
});

Press the button below to action the above code:


Get the content document of an iframe that is on the same domain as the page we are using it in.

In the example below we locate the iframe with an id of 'ourIframe' and change the background colour of the '#main' content to olive.





$(function(){
  $('#btn15').on('click', function() {
    $('#ourIframe').contents()
                   .find('#main')
                   .css('backgroundColor', 'olive');  
  });
});

Press the button below to action the above code: