I have a big HTML-string containing multiple child-nodes.
Is it possible to construct a jQuery DOM object using this string?
I've tried $(string)
but it only returns an array containing all the individual nodes.
Imtrying to get an element which i can use the .find() function on.
This question is related to
javascript
jquery
html
There is also a great library called cheerio designed specifically for this.
Fast, flexible, and lean implementation of core jQuery designed specifically for the server.
var cheerio = require('cheerio'),
$ = cheerio.load('<h2 class="title">Hello world</h2>');
$('h2.title').text('Hello there!');
$('h2').addClass('welcome');
$.html();
//=> <h2 class="title welcome">Hello there!</h2>
the reason why $(string) is not working is because jquery is not finding html content between $(). Therefore you need to first parse it to html. once you have a variable in which you have parsed the html. you can then use $(string) and use all functions available on the object
You can try something like below
$($.parseHTML(<<table html string variable here>>)).find("td:contains('<<some text to find>>')").first().prev().text();
As of jQuery 1.8 you can just use parseHtml to create your jQuery object:
var myString = "<div>Some stuff<div>Some more stuff<span id='theAnswer'>The stuff I am looking for</span></div></div>";
var $jQueryObject = $($.parseHTML(myString));
I've created a JSFidle that demonstrates this: http://jsfiddle.net/MCSyr/2/
It parses the arbitrary HTML string into a jQuery object, and uses find to display the result in a div.
I use the following for my HTML templates:
$(".main").empty();
var _template = '<p id="myelement">Your HTML Code</p>';
var template = $.parseHTML(_template);
var final = $(template).find("#myelement");
$(".main").append(final.html());
Note: Assuming if you are using jQuery
var jQueryObject = $('<div></div>').html( string ).children();
This creates a dummy jQuery object in which you can put the string as HTML. Then, you get the children only.
Source: Stackoverflow.com