Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the string representation of a jquery DOM object's entire HTML

Tags:

jquery

dom

I have had a bit of a look around and am having some difficulty solving a wee issue I am having.

I basically have a string of HTML, I convert that to a JQuery DOM object so that I can easily remove all elements that have a certain class using JQuery's .remove(). I.e.,

var radHtml = editor.get_html();

var jqDom = $(radHtml);

$(".thickbox", jqDom).remove();
$(".thickboxcontent", jqDom).remove();

editor.set_html(this.innerHTML);

NOTE: The HTML is derived from content in a RADEditor text editor so there are no parent HTML tags, so can look as follows:

<p>This is a header</p>
<p>this is some content followed by a table </p>
<a href="#TB_inline?height=350&amp;width=400&amp;inlineId=myOnPageContent0" class="thickbox">Test Thickbox</a>
<div id="myOnPageContent0" class="thickboxcontent">
<table class="modal">
    <thead>
    </thead>
    <tbody>
        <tr>
            <td>item</td>
            <td>result</td>
        </tr>
        <tr>
            <td>item 1</td>
            <td>1</td>
        </tr>
        <tr>
            <td>item 2</td>
            <td>2</td>
        </tr>
        <tr>
            <td>item 3</td>
            <td>3</td>
        </tr>
    </tbody>
</table>
</div>

Here is what the jqDom.html() returns from the HTML above:

"This is a header"

I was wondering if there was an easy way to do this - have some html and remove all elements (in this case divs) that have a certain class (but leaving their contents). JQuery doesnt have to used, but I would like to.

Manipulating the DOM object is fine - it is getting the full DOM object in its entirety as a string that I am having the problem with.

Any help would be much appreicated. Thanks.

like image 948
Scott Avatar asked Jun 07 '10 03:06

Scott


2 Answers

If you want the html of each matching element to your selector, try doing a map :

var allHtmls = jqDom.find('.thickbox').map(function(){ 
  return this.innerHTML; 
});

Also, it sounds like you might want to use unwrap which was added to jQuery 1.4+ ( http://api.jquery.com/unwrap/ )

jqDom.find('.thickbox').children().unwrap();

like image 196
Alex Sexton Avatar answered Oct 19 '22 07:10

Alex Sexton


var radHtml = editor.get_html();

var jqDom = $(radHtml);
jqDom.wrap('div'); //dont remember if thats ok or u need to asign it in the jqDom again
$(".thickbox", jqDom).remove();
$(".thickboxcontent", jqDom).remove();

editor.set_html(jqDom.html());

Maybe that could help

like image 39
Juan Techera Avatar answered Oct 19 '22 07:10

Juan Techera