LukeHennerley
LukeHennerley

Reputation: 6444

Selecting all content from sub elements of a div

If I have a div element like so:

<div id="someContents">
    <p>Foo has the following properties</p>
    <ul>
        <li>Bar</li>
    </ul>
    <p>And some other stuff</p>
</div>

And declare this:

var $someContents = $('#someContents');

Then I want to declare a now var which will be a single String and will have the contents that you see on screen with line breaks etc.

http://jsfiddle.net/7a5b9/

I have tried various JQuery methods... Any suggestions appreciated.

Upvotes: 0

Views: 33

Answers (3)

Code Maverick
Code Maverick

Reputation: 20415

var $someContents = $('#someContents').html();
alert($someContents);

This gets all of the HTML content and yields:

enter image description here

http://jsfiddle.net/dFB3J/


var $someContents = $('#someContents').text();
alert($someContents);

This gets all of the inner text content and yields:

enter image description here

http://jsfiddle.net/z2f26/


(function($){
   $.fn.innerText = function(msg) {
         if (msg) {
            if (document.body.innerText) {
               for (var i in this) {
                  this[i].innerText = msg;
               }
            } else {
               for (var i in this) {
                  this[i].innerHTML.replace(/&amp;lt;br&amp;gt;/gi,"n").replace(/(&amp;lt;([^&amp;gt;]+)&amp;gt;)/gi, "");
               }
            }
            return this;
         } else {
            if (document.body.innerText) {
               return this[0].innerText;
            } else {
               return this[0].innerHTML.replace(/&amp;lt;br&amp;gt;/gi,"n").replace(/(&amp;lt;([^&amp;gt;]+)&amp;gt;)/gi, "");
            }
         }
   };
})(jQuery);

var $someContents = $('#someContents').innerText();
alert($someContents);

This gets all of the inner text content (preserving line breaks) and yields:

enter image description here

http://jsfiddle.net/4gpLE/

Source: http://www.sitepoint.com/jquery-text-function/

Upvotes: 1

Think Different
Think Different

Reputation: 2815

Try this:

var now = $(someContents).find('*').text();

Upvotes: 2

Rafael Brasil
Rafael Brasil

Reputation: 232

This question was answered here

A simple way is to create a temporary clone of your html, put it inside another tag and get the text or html content.

$('<div>').append($('#xxx').clone()).html();

Upvotes: 0

Related Questions