0

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.

LukeHennerley
  • 6,344
  • 1
  • 32
  • 50

3 Answers3

2

Try this:

var now = $(someContents).find('*').text();
Think Different
  • 2,815
  • 1
  • 12
  • 18
1
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/

Code Maverick
  • 20,171
  • 12
  • 62
  • 114
0

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();
Community
  • 1
  • 1
Rafael Brasil
  • 232
  • 1
  • 6