How to get a HTML element from a string with jQuery

JavascriptJqueryHtml

Javascript Problem Overview


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

I have a Javascript function that gets an entire page from the server, but I only need one element from that page.

Javascript Solutions


Solution 1 - Javascript

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

var elements = $(theHtmlString);
var found = $('.FindMe', elements);

Solution 2 - Javascript

Just wrap the html text in the $ function. Like

$("<div>I want this element</div>")

Solution 3 - Javascript

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.

Solution 4 - Javascript

Just use $.filter

var html = "<div><span class='im-here'></span></div>"
var found = $(html).filter(".im-here")

Solution 5 - Javascript

You can use $.find

$(document).ready(function() {
  var htmlVal = "<div><span class='im-here'>Span Value</span></div>";
  var spanElement = $(htmlVal).find("span");
  var spanVal = spanElement.text();
  
  alert(spanVal);
});

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRaphaelView Question on Stackoverflow
Solution 1 - JavascriptGuffaView Answer on Stackoverflow
Solution 2 - JavascriptKingErroneousView Answer on Stackoverflow
Solution 3 - JavascriptPeter AjtaiView Answer on Stackoverflow
Solution 4 - Javascriptjayson.centenoView Answer on Stackoverflow
Solution 5 - JavascripthiFIView Answer on Stackoverflow