JQuery get html as jQuery workaround

This is a very simple question that I just cannot find in order to find a good answer.

$.get('/myurl.html', function(response){ console.log(response); //works! console.log( $(response).find('#element').text() ); //null :( }, 'html'); 

I am just trying to execute my html answer. So far, the only thing I can think about is a regular expression inside body tags and use it as a string to create a traversable jQuery object. But it just seems stupid. Anyone have to point out the correct way to do this?

Maybe its my html?

 <html> <head> <title>Center</title> </head> <body> <!-- tons-o-stuff --> </body> </html> 

This also works great, but doesn't suit my needs:

$ ('# myelem'). load ('/myurl.html #element');

+6
source share
4 answers

It fails because it doesn’t like <html> and <body> .

Using the method described here: JavaScript parser for the DOM

 $.get('/myurl.html', function(response){ var doc = document.createElement('html'); doc.innerHTML = response; console.log( $("#element", doc).text() ); }, 'html'); 

I think the above should work.

+7
source

When jQuery parses HTML, it usually strips out the html and body tags, so if the element you are looking for is at the top level of your document structure after you remove the html and body tags, the find function may not be able to find the element you are looking for.

See this question for more information - Using jQuery to find an HTML string

+1
source

Try the following:

 $("#element", $(response)).text() 

This searches for the element identifier in $ (response), treating $ (response) as a DOM object.

0
source

Maybe I don’t understand something, but

 .find('#element') 

matches elements with the identifier "element", for example

 <p id="element"> 

Since I don’t see the “tons of things” of HTML, I don’t understand what elements you are trying to find.

-1
source

Source: https://habr.com/ru/post/912519/


All Articles