Reputation: 6444
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.
I have tried various JQuery methods... Any suggestions appreciated.
Upvotes: 0
Views: 33
Reputation: 20415
var $someContents = $('#someContents').html();
alert($someContents);
This gets all of the HTML content and yields:
var $someContents = $('#someContents').text();
alert($someContents);
This gets all of the inner text content and yields:
(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(/&lt;br&gt;/gi,"n").replace(/(&lt;([^&gt;]+)&gt;)/gi, "");
}
}
return this;
} else {
if (document.body.innerText) {
return this[0].innerText;
} else {
return this[0].innerHTML.replace(/&lt;br&gt;/gi,"n").replace(/(&lt;([^&gt;]+)&gt;)/gi, "");
}
}
};
})(jQuery);
var $someContents = $('#someContents').innerText();
alert($someContents);
This gets all of the inner text content (preserving line breaks) and yields:
Source: http://www.sitepoint.com/jquery-text-function/
Upvotes: 1
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