orezvani
orezvani

Reputation: 3775

How to select elements from an html string using jquery

I am using jquery to get the data from one web page and show it in another page. Basically, I have a string that includes the html code of the page such as:

var str = '<head><title>some title</title><head><body><div class="main"><div id="inner"></div></div></body>';

and I need to get the content of "#inner" from str. How to is this possible? I am looking for some solution that is fast, short and without using a lot of memory.

Upvotes: 0

Views: 158

Answers (2)

void
void

Reputation: 36703

You can build HTML Elements from strings..

var str = '<head><title>some title</title><head><body><div class="main"><div id="inner"></div></div></body>';
var a = $(str);
var _innerHTML = a.find("#inner").html();

Upvotes: 0

Brennan
Brennan

Reputation: 5732

jQuery allows you to build HTML from strings, so you can just find the element within:

var str = '<head><title>some title</title><head><body><div class="main"><div id="inner"></div></div></body>';
$(str).find('#inner');

This works as long as you're looking for DOM elements. This will not handle the <head/> of the document.

Upvotes: 1

Related Questions