Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
132
rated 0 times [  136] [ 4]  / answers: 1 / hits: 29422  / 12 Years ago, sun, january 20, 2013, 12:00:00

I'm making an ajax call to fetch content and append this content like this:



$(function(){
var site = $('input').val();
$.get('file.php', { site:site }, function(data){
mas = $(data).find('a');
mas.map(function(elem, index) {
divs = $(this).html();
$('#result').append('' + divs + '');
})
}, 'html');
});


The problem is that when I change a in body I get nothing (no error, just no html). Im assuming body is a tag just like 'a' is? What am I doing wrong?



So this works for me:



 mas = $(data).find('a');


But this doesn't:



 mas = $(data).find('body');

More From » jquery

 Answers
22

Parsing the returned HTML through a jQuery object (i.e $(data)) in order to get the body tag is doomed to fail, I'm afraid.



The reason is that the returned data is a string (try console.log(typeof(data))). Now, according to the jQuery documentation, when creating a jQuery object from a string containing complex HTML markup, tags such as body are likely to get stripped. This happens since in order to create the object, the HTML markup is actually inserted into the DOM which cannot allow such additional tags.



Relevant quote from the documentation:




If a string is passed as the parameter to $(), jQuery examines the string to see if it looks like HTML.



[...]
If the HTML is more complex than a single tag without attributes, as it is in the above example, the actual creation of the elements is handled by the browser's innerHTML mechanism. In most cases, jQuery creates a new element and sets the innerHTML property of the element to the HTML snippet that was passed in. When the parameter has a single tag (with optional closing tag or quick-closing) — $( < img / > ) or $( < img > ), $( < a >< /a > ) or $( < a > ) — jQuery creates the element using the native JavaScript createElement() function.



When passing in complex HTML, some browsers may not generate a DOM
that exactly replicates the HTML source provided. As mentioned, jQuery
uses the browsers .innerHTML property to parse the passed HTML and
insert it into the current document. During this process, some
browsers filter out certain elements such as < html >, < title >, or
< head > elements. As a result, the elements inserted may not be
representative of the original string passed.



[#80749] Friday, January 18, 2013, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
neildrews

Total Points: 166
Total Questions: 103
Total Answers: 85

Location: Moldova
Member since Sat, Aug 6, 2022
2 Years ago
neildrews questions
Fri, Feb 18, 22, 00:00, 2 Years ago
Tue, Oct 12, 21, 00:00, 3 Years ago
Tue, Mar 23, 21, 00:00, 3 Years ago
Sun, Aug 16, 20, 00:00, 4 Years ago
;