0

I am attempting to grab a child element of HTML loaded dynamically via AJAX. It is not working.

 $.get('test.html', function(data) {

    var content = $('#content', data).html();

    console.log(content); // Logs "Null"

    $('#result').html(content);

  });

Here is the 'test.html'

<!DOCTYPE html>
<html lang="en" >
<head>
  <meta charset="UTF-8" />
  <title>Website</title>
  <meta name="description" content="" />
  <meta name="keywords" value="" />
</head>
<body>

  <h1>Hello!!!</h1>

  <div id="content">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam feugiat tincidunt tortor eu iaculis. Sed id urna sem, quis malesuada lacus. Nulla iaculis malesuada libero, id vehicula sapien imperdiet eu.</div>

</body>
</html>

Also, if I try this: console.log($(data));, Firebug gives me this:

[<TextNode textContent="\n\n\n ">, meta, <TextNode textContent="\n ">, title, <TextNode textContent="\n ">, meta, <TextNode textContent="\n ">, meta, <TextNode textContent="\n\n\n \n ">, h1, <TextNode textContent="\n \n ">, div#content, <TextNode textContent="\n\n\n\n">]

Any ideas???

2
  • where is the #content in the html file ? Commented Dec 20, 2011 at 21:08
  • Sorry... #holder was meant to be #content. I fixed above. Commented Dec 20, 2011 at 21:19

3 Answers 3

1

You made a mistake with the content var i believe, it doesnt make sense.

 $.get('test.html #content', function(data) {
 console.log(data); // Logs "Null"
 $('#result').html(data);
 });

thats how jquery website would say to do it.

I say use

$('#result').load('test.html #content'); 

hows that for ya?

Sign up to request clarification or add additional context in comments.

Comments

0

try using $.ajax instead:

 $.ajax({
   url:'test.html', 
   dataType:'html',
   success:function(data) {
    var content = $('#content', data).html();
    console.log(content); // Logs "Null"
    $('#result').html(content);
   }
  });

2 Comments

Yeah, it gives me the same results too.
Correct. I wanted to be able to identify the name of the parameters though. The main point being to identify the dataType in case jQuery is not properly determining the data type from the MIME type in the response.
0

I'm not quite clear on what you're trying to do, but I'm assuming you want to get the contents of #content in your test.html page and inject that into your #results div.

$.get('test.html', function(data) {
    var content = $(data).find("#content").html();
    $('#result').html(content);
});

3 Comments

Sorry... #holder was meant to be #content. I fixed above. Anyway, I tried your suggestion, and content still logs out as null.
What happens when you console.log(data) in the callback?
It looks as you'd expect... the contents of the file.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.