.contents()

Get the children of each element in the set of matched elements, including text and comment nodes.

.contents()🡢 jQuery

Given a jQuery object that represents a set of DOM elements, the .contents() method allows us to search through the immediate children of these elements in the DOM tree and construct a new jQuery object from the matching elements. The .contents() and .children() methods are similar, except that the former includes text nodes and comment nodes as well as HTML elements in the resulting jQuery object. Please note that most jQuery operations don't support text nodes and comment nodes. The few that do will have an explicit note on their API documentation page.

The .contents() method can also be used to get the content document of an iframe, if the iframe is on the same domain as the main page.

As of jQuery 3.2, .contents() returns contents of <template> elements as well.

Consider a simple <div> with a number of text nodes, each of which is separated by two line break elements (<br>):

<div class="container">
  Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
  tempor incididunt ut labore et dolore magna aliqua.
  <br /><br />
  Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
  aliquip ex ea commodo consequat.
  <br /><br />
  Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore
  eu fugiat nulla pariatur.
</div>

We can employ the .contents() method to help convert this blob of text into three well-formed paragraphs:

$(".container")
  .contents()
  .filter(function () {
    return this.nodeType === 3;
  })
  .wrap("<p></p>")
  .end()
  .filter("br")
  .remove();

This code first retrieves the contents of <div class="container"> and then filters it for text nodes, which are wrapped in paragraph tags. This is accomplished by testing the .nodeType property of the element. This DOM property holds a numeric code indicating the node's type; text nodes use the code 3. The contents are again filtered, this time for <br /> elements, and these elements are removed.

Find all the text nodes inside a paragraph and wrap them with a bold tag.

JS
<p>Hello <a href="https://johnresig.com/">John</a>, how are you doing?</p>
HTML
$("p")
  .contents()
  .filter(function () {
    return this.nodeType !== 1;
  })
  .wrap("<b></b>");
DEMO

Change the background color of links inside of an iframe.

JS
<iframe
  src="https://api.jquery.com/"
  width="80%"
  height="600"
  id="frameDemo"
></iframe>
HTML
$("#frameDemo").contents().find("a").css("background-color", "#BADA55");
DEMO

Looking for a Web Developer?

👋

Hi! I'm Basti, author of this site. If you are looking for a web developer with 15+ years of experience, holla at me!

Be it the good 'ol jQuery, vanilla JS or modern frameworks like Vue and Svelte, front- or backend, I can help you.

Just write me at jobs@jqapi.com :)