170

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.

6
  • Where is the HTML, what do you want to construct with it? You may want to look at the .find() function: api.jquery.com/find Commented Jun 15, 2012 at 9:08
  • 3
    A jQuery object is an array-like object containing all the nodes. Can you elaborate on what you're trying to achieve? Commented Jun 15, 2012 at 9:09
  • 2
    Where is 'this string'? what string? Commented Jun 15, 2012 at 9:10
  • Take a look here,I think it is what you want stackoverflow.com/q/759887/474535 Commented Jun 15, 2012 at 9:12
  • I have to pass the element from one WebView to another through a string, the string would just be the HTML source of that element. I think i might have missunderstood what a jQuery object is. Commented Jun 15, 2012 at 9:14

9 Answers 9

246

Update:

From jQuery 1.8, we can use $.parseHTML, which will parse the HTML string to an array of DOM nodes. eg:

var dom_nodes = $($.parseHTML('<div><input type="text" value="val" /></div>'));

alert( dom_nodes.find('input').val() );

DEMO


var string = '<div><input type="text" value="val" /></div>';

$('<div/>').html(string).contents();

DEMO

What's happening in this code:

  • $('<div/>') is a fake <div> that does not exist in the DOM
  • $('<div/>').html(string) appends string within that fake <div> as children
  • .contents() retrieves the children of that fake <div> as a jQuery object

If you want to make .find() work then try this:

var string = '<div><input type="text" value="val" /></div>',
    object = $('<div/>').html(string).contents();

alert( object.find('input').val() );

DEMO

Sign up to request clarification or add additional context in comments.

7 Comments

@user1033619 you can perform .find() operation also, check the demo
But how if string = '<input type="text" value="val" />'
If you can do $("<div/>"), why can't you do $(string)?
With more complex HTML I needed to remove .contents to get this to work. jsfiddle.net/h45y2L7v
You don't want to do $(string) because you need a wrapping div to get the contents of. You'll be getting the contents of the div, which will be your input.
|
128

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.

9 Comments

I find this answer far better, since this don't have to use a ghost div element. $.parseHtml ftw.
This answer didn't work for me when I wanted then then to $jQueryObject.find(), I presume because it wasn't added to the dom at that point.
@dougajmcdonald -- find should work without the content being added to the dom. If you take a look at my fiddle (jsfiddle.net/MCSyr/2), I'm calling find on the jQuery object, and it returns a result as expected: $jQueryObject.find("#theAnswer").html()
@kiprainey interesting, I'll dig out the example it didn't for me on and see if there was something else afoot. It was written inside a TypeScript module inside a load of other logic, could well have been a different issue! My apologies.
Worth mentioning that parseHTML was added in jQuery 1.8
|
13
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.

2 Comments

ive tried this, but it doesnt work with the .find() function i have to use later.
@user1033619 you got to use .filter() instead of .find().
2

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>

Comments

2

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

Comments

1

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

Comments

0

You can try something like below

$($.parseHTML(<<table html string variable here>>)).find("td:contains('<<some text to find>>')").first().prev().text();

Comments

0

I know this is an old thread, but I have another simple answer. jQuery has moved up quite a few versions and I'm on 1.13.x

Not being an expert jQuery programmer, I näively used:

var el = $( "#thecontainer" ).append( "<legit, lengthy html>" );

And presto! It worked: el is now a fully operational jQuery dom element.

I have been testing it out over the past couple of days and it seems to work as expected.

Comments

0

Why it alerts as 0 length ?

$(function(){   
 

var rrr=$('<html><body><div class="new">aaaa</div></body></html>');
    
alert(rrr.find('.new').length)  //return 0


})    
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.