如何使用jQuery从字符串中获取HTML元素

时间:2022-01-17 13:38:38

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?

我正在寻找一种从包含HTML的字符串中获取HTML元素的方法。是否可以使用jQuery选择器来执行此操作?

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

基本上我有一个javascript函数从服务器获取整个页面,但我只需要该页面中的一个元素。

Thanks in advance

提前致谢

4 个解决方案

#1


66  

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

是的,您可以将字符串转换为元素,然后从中选择元素。例:

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

#2


17  

Just wrap the html text in the $ function. Like

只需将html文本包装在$函数中即可。喜欢

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

#3


9  

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()

如果从服务器动态加载页面,则可以使用以下形式使用.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.

其中:#result是加载的页面部分将显示在当前页面上的位置ajax / test.html是服务器请求发送到的URL #container是要显示的响应页面上的元素。只有那将被加载到元素#result中。其余的响应页面将不会显示。

#4


5  

Just use $.filter

只需使用$ .filter

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

#1


66  

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

是的,您可以将字符串转换为元素,然后从中选择元素。例:

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

#2


17  

Just wrap the html text in the $ function. Like

只需将html文本包装在$函数中即可。喜欢

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

#3


9  

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()

如果从服务器动态加载页面,则可以使用以下形式使用.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.

其中:#result是加载的页面部分将显示在当前页面上的位置ajax / test.html是服务器请求发送到的URL #container是要显示的响应页面上的元素。只有那将被加载到元素#result中。其余的响应页面将不会显示。

#4


5  

Just use $.filter

只需使用$ .filter

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