jQuery API

.contents()

.contents() Returns: jQuery

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

  • version added: 1.2.contents()

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 as well as HTML elements in the resulting jQuery object.

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.

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.

Examples:

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

<!DOCTYPE html>
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  <p>Hello <a href="http://ejohn.org/">John</a>, how are you doing?</p>
<script>$("p").contents().filter(function(){ return this.nodeType != 1; }).wrap("<b/>");</script>

</body>
</html>

Demo:

Example: Change the background colour of links inside of an iframe.

<!DOCTYPE html>
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  <iframe src="http://api.jquery.com/" width="80%" height="600" id='frameDemo'></iframe> 
<script>$("#frameDemo").contents().find("a").css("background-color","#BADA55");</script>

</body>
</html>

Demo:

Support and Contributions

Need help with .contents() or have a question about it? Visit the jQuery Forum or the #jquery channel on irc.freenode.net.

Think you've discovered a jQuery bug related to .contents()? Report it to the jQuery core team.

Found a problem with this documentation? Report it on the GitHub issue tracker

  • http://twitter.com/lynt Karl Stanton

    I found this very useful with trying to access an iFrame as seen in this blog post:

    http://simple.procoding.net/2008/03/21/how-to-a…

    • kox

      The correct answer is cbsides's reply I think.

      var myFrame = $('#myFrameId');
      myFrame.load(function(){
      myFrame.contents().find('a').css(“background-color”,”#f33″);
      });

      • kox

        it works only relative path.

  • tibi7000

    The example won’t work for sure unless the iframe is done loading. The code in the script should be:

    $(“#frameDemo”).load({
    $(this).contents().find(“a”).css(“background-color”,”#BADA55″);
    });

    • Greg

      Should be like this
      $('iframe').load(function() {
      $(“iframe”).contents().find(“body#tinymce”).css(“background-color”,”green”);
      });

      or
      $('iframe').ready(function() {
      $(“iframe”).contents().find(“body#tinymce”).css(“background-color”,”green”);
      });

  • http://twitter.com/maujor maujor

    Description for this method says: …including text nodes.
    Shouldn’t be?: …including text nodes, and comments nodes.
    Doing some tests here, it seems that attributes nodes isn’t returned!
    Others nodes not tested.
    Or, am I missing something?

  • Duong Nguyen

    access denied, if content of iFrame is other source

  • can

    The example work, if adding “ready” function.

    $(document).ready(function(){
    $(“#frameDemo”).contents().find(“a”).css(“background-color”,”#BADA55″);
    });

  • Neeraj

    Dynamically added script tag in iframe is not visible / nor exceuting

    e.g : $(“#id” ).contents().find(“scriptContainer”).append(“<script type='text/javascript'>alert('test');</script>”);

    • lasiu

      Try use .find(“.scriptContainer”) – if handle is a class

  • Aladjev Andrew

    I dont understand how to get full content of iframe
    $(iframe).contents().text() – right text but without tags
    $(iframe).contents().html() – null
    $(iframe).contents().val() – clear

    • bl

      Did You try $(iframe).contents().find('html body').html() ?

  • vativa

    Hi, there,
    trigger('click') doesn't work in iframe in Firefox 3.6 ???

    $('iframe#fielupload_iframe').contents().find('input#iFile').trigger('click');

    :( Safari do trigger, Firefox doesn't :(

  • Dani Leonhartsberger

    how about the cross-domain access?

  • Indie

    >> $(“iframe”).contents().find('html')
    It doesn't work in Great Browser Goooogle CHROME :-@

    • http://pulse.yahoo.com/_7TAFKN5ILSWMRD4PWTFJ6NR35E Manu

      Some “great” browser that one is.

    • Charles

      You should open the chrome error console to check. I did that, and there is an error says: “Unsafe JavaScript attempt to access frame with URL http://www.example.com/
      from frame with URL chrome-ui://inspector/inspector.html. Domains,
      protocols and ports must match”. So you need to check your page and the iframe src are from the same server or not.

      And if you test it locally will not be fine via “file://” url. When I try using 2 pages by clicking then to open up, the same error happened again.

      Hope that helps.

  • Renato Fabro

    Resolved!

    Hello, I was trying to read the html in an iframe.
    It did not work because the html tags do not come in the text ();
    Then decided to encode html in php with 'htmlentities ($ errH, ENT_NOQUOTES,' UTF-8 '),' and so when I was reading with. text () content of the iframe, html came to me.

    TryIt!

  • Xman-2009

    ้ha ha ha “great” browser

  • Alex_wem

    I want to get the iframe 's width.

    <iframe id=”myiframe” src=”content.html”>

    if the content.html page 's width is change

    I want change the iframe's with the iframe.

    what can i do?</iframe>

  • Jonathan

    cool effect but was wondering….if i have click on a link…the effect would be gone…how do i make the jquery constantly attached to every page in the link..

  • http://www.vainfotech.com Website Design India

    nice List

  • Privadojoel

    rit=$(“#url_doctor”).contents().find(“textarea”).attr(“value”);
    rit2=$('#url_doctor').contents().find(“#urlShare”).find(“textarea”).attr(“value”);

    my iframe : <iframe id=”url_doctor” name=”url_doctor” src=”http://ubiqq.com/”></iframe>

    I want to hold the value of the textarea called text_area, but I do not return
    no value.

    help!!!!!