Search code examples
javascriptjquerynodes

jQuery find().html() returns undefined


I am new to JS, this is what I was doing.

I have a rawHtml string, which is just html, when I do

$(rawHtml).find('#footer')

and I log this, this is what it returns

jQuery {
'0': HTMLDivElement {},
'1': HTMLDivElement {},
'2': HTMLDivElement {},
'3': HTMLDivElement {},
'4': HTMLDivElement {},....}

So I know for sure it's not empty. But if I do this

$(rawHtml).find('#footer').html()

it returns undefined. I just want to print out the html, Is there other ways I can do this? And why is it printing undefined?

EDIT

The html is very long, the basic structure is like this:

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
<title>Title</title>
<link rel="stylesheet" type="text/css" href="some link">
<link rel="stylesheet" type="text/css" href="some link">
<link rel="stylesheet" type="text/css" href="some link ">
<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="css/animate.css">
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
</html>

For simplicity purposes, footer is waaaay down and more complex, for head it's the same thing, if I do

$(rawHtml).find('head').html()

returns undefined as well.


Solution

  • The only reason html would return undefined would be if you called it on an empty jQuery set, so that tells us that find isn't finding anything.

    find looks within the descendants of the entries in the jQuery set. It looks like your #footer is directly in the set (at the top level); that commony happens when you use $() to parse HTML. If so, you want filter rather than find.

    Example:

    var rawHTML =
      "<div id=header>header content</div>" +
      "<div id=footer>footer content</div>";
    var footerText = $(rawHTML).filter("#footer").html();
    console.log(footerText);
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

    Or, if you're not sure whether the element will be at the top level or a descendant, wrap the whole thing in a div and use find:

    var rawHTML =
      "<div id=header>header content</div>" +
      "<div id=footer>footer content</div>";
    var footerText = $("<div>").append(rawHTML).find("#footer").html();
    console.log(footerText);
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>