views:

53

answers:

3

I'm looking for a way to get an HTML element from a string that contains HTML. Is it possible to use the jQuery selector to do this?

Basically I have an javascript functions that get an entire page from the server but I only need one element from that page.

Thanks in advance

+2  A: 

Just wrap the html text in the $ function. Like

$("<div>I want this element</div>")
KingErroneous
+3  A: 

Yes, you can turn the string into elements, and select elements from it. Example:

var elements = $(theHtmlString);
var found = $('.FindMe', elements);
Guffa
This is called using `elements` as the [ **context** ](http://api.jquery.com/jQuery/). It is internally implemented with [ **.find()** ](http://api.jquery.com/find/) , so an equivalent way to write the above is: `var found = elements.find('.FindMe');`
Peter Ajtai
+2  A: 

If you are loading a page dynamically from a server then you can target just one element from the loaded page using the following form with .load()

$(selectorWhereToShowNewData).load('pagePath selectorForElementFromNewData');

For example:

$('#result').load('ajax/test.html #container');

Where:
#result is where the loaded page part will be displayed on the current page
ajax/test.html is the URL to which the server request is sent
#container is the element on the response page you want to display. Only that will be loaded into the element #result. The rest of the response page will not be displayed.

Peter Ajtai