jQuery.parseHTML()
produces an array. I'm looking for a way to convert it back to string. This is my top question.
Is parseHTML()
the only method to treat a string as html?
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?
This parseHTML () Method in jQuery is used to parses a string into an array of DOM nodes. Parameters: The parseXML () method accepts three parameter that is mentioned above and described below:
jQuery.parseHTML (data context ] [, keepScripts ]) Parameters: The parseXML () method accepts three parameter that is mentioned above and described below: data: This parameter is the HTML string to be parsed. context : This parameter is the document element to serve as the context in which the HTML fragment will be created.
Return Value: It returns the Array. Example 1: In this example, the parseHTML () Method a string is parsed into an array of DOM nodes. Example 2: In this example, the parseHTML () Method create an array of DOM nodes using an HTML string and insert it into a div.
Parameters: The parseXML () method accepts three parameter that is mentioned above and described below: data: This parameter is the HTML string to be parsed. context : This parameter is the document element to serve as the context in which the HTML fragment will be created.
function htmlToSource(selector){
return $('<div />').append($(selector).clone()).html();
};
htmlToSource('body');
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');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With