Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 254
Iryn Avatar asked Nov 21 '13 21:11

Iryn


People also ask

What is parsehtml () method in jQuery?

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:

How do I parse an HTML string in jQuery?

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.

What is the return value of parsehtml ()?

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.

What are the parameters of parse XML?

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.


2 Answers

A simple function

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

htmlToSource('body');
like image 57
Randy Stiven Valentín Avatar answered Oct 12 '22 20:10

Randy Stiven Valentín


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');
like image 1
jbabey Avatar answered Oct 12 '22 22:10

jbabey