Method contents

The contents method gets the descendants of an element, including text and comments.

Syntax

The method does not take parameters:

javascript.contents();

The contents method works similarly to the children method, the difference appears when trying to access the text of children. Compare the two examples below:

Example

We use the children method:

html<p id="test">text1 <b>bold</b> text2</p>
javascript$('#test').children().each(
  function() {
    console.log($(this).text()); // will bring out 'bold'
  }
);

Example

We use the contents method:

html<p id="test">text1 <b>bold</b> text2</p>
javascript$('#test').contents().each(
  function() {
    console.log($(this).text()); // will bring out 'text1', 'bold', 'text2'
  }
);

See also

  • method children,
    which allows you to get the descendants of an element
  • method parent,
    which allows you to get the immediate parent of an element
  • method parents,
    which allows you to get all the parents of an element
  • method closest,
    which allows you to get the closest parent element that satisfies the selector