Iryn
Iryn

Reputation: 255

reverse of jQuery.parseHTML

  1. jQuery.parseHTML() produces an array. I'm looking for a way to convert it back to string. This is my top question.

  2. Is parseHTML() the only method to treat a string as html?

  3. Bassically, I was parsing my string as html so that I can use find() function of jQuery to match a certain element and then perfrom a replacement only on that portion of the code (see my previous question for more details). So, is parsing to html necessary for that?

Upvotes: 7

Views: 11190

Answers (5)

A simple function

function htmlToSource(selector){
 return $('<div />').append($(selector).clone()).html();
};

htmlToSource('body');

Upvotes: 3

Doglas
Doglas

Reputation: 670

This is a simple way to resolve the top question:

var $html = $($.parseHTML(html));//transform html string into a jQuery element
$html.append('<div id="other_test"></div>');//handling
console.log("string again, but edited", $html.get(0).outerHTML);//converting it to string again

Upvotes: 1

flipper
flipper

Reputation: 146

when i was trying to convert back from html object to string in my page i was not able to using the function

var my_variable="$("<div></div>");
$("my_variable").html();

then i found the trick of doing that using the code below. it was really tricky

Example if you want to convert the "mySet" from the above comment variable back to string you can use this

 $(mySet).html($(mySet).clone()).html();

Upvotes: 2

Justin Niessner
Justin Niessner

Reputation: 245459

  1. jQueryElement.outerHTML();

  2. No. You can also use the jQuery shortcut: $('<input type="submit" />');

  3. No. You could also try string manipulation but there's a good chance that the jQuery method will be easier and more reliable.

Upvotes: 1

jbabey
jbabey

Reputation: 46657

Sounds like you want to just construct some DOM elements on the fly. You can do that by just passing an HTML string to the jQuery function ($()). No parseHTML() required.

var mySet = $('<div>blah blah blah<span>some stuff</span></div>');

// perform operations on the set just like you would a regular jQuery set
var divsInMySet = mySet.find('div');

// be aware some functions will return unexpected results since your set exists in memory not on the page
// for example anything related to positioning or visibility will fail
var whoKnows = mySet.position();
var dontDoThis = mySet.is(':visible');

Upvotes: 1

Related Questions