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.
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.
Yes, you can turn the string into elements, and select elements from it. Example:
var elements = $(theHtmlString);
var found = $('.FindMe', elements);
elements as the [ context ](api.jquery.com/jQuery). It is internally implemented with [ .find() ](api.jquery.com/find) , so an equivalent way to write the above is: var found = elements.find('.FindMe');$('selector', $('html string'))) doesn't seem to work for me in jQ:1.6.2find(), whereas I needed it to use closest(), perhaps jQ should be amended. Problem Case: $('pre', $('<pre><div>foo</div></pre><pre><div>bar</div></pre>'));. Because it uses find, which only looks at the children, it'll never find any pres. Easiest solution is to add a wrap.$(theHtmlString).find('.FindMe') ?elements.find(selector) does the same as $(selector, elements).Just wrap the html text in the $ function. Like
$("<div>I want this element</div>")
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.
Just use $.filter
var html = "<div><span class='im-here'></span></div>"
var found = $(html).filter(".im-here")
filter method works even if the element you want happens to be the outer-most element. The find method only finds descendants, so it would not match the outer-most element. In the example in this answer, you could not use the find method to get the div.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);
});
$.find—but only if you want just elements inside the outermost element, the div' in this example. The find` method only matches descendants. You could not find the div in this example--but, you can filter the div because the filter method matches any/all elements, including the outermost div.