.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_NODE | 1 | ATTRIBUTE_NODE | 2 |
TEXT_NODE | 3 | CDATA_SECTION_NODE | 4 |
ENTITY_REFERENCE_NODE | 5 | ENTITY_NODE | 6 |
PROCESSING_INSTRUCTION_NODE | 7 | COMMENT_NODE | 8 |
DOCUMENT_NODE | 9 | DOCUMENT_TYPE_NODE | 10 |
DOCUMENT_FRAGMENT_NODE | 11 | NOTATION_NODE | 12 |
.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');
});
});
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');
});
});