jQuery html() undefined for DOM object

I have never seen this behave like this, but I am stumped as to how to fix it.

Here is my HTML:

<div id="display">
		<script src="scripts/gallery_init.js"></script>
</div>
<div id="likes"></div>

And this is the code for gallery_init.js:

if (!HAS_QS) {
	$('#display').append(`<link rel="stylesheet" type="text/css" href="stylesheets/gallery_styles.css" />`);
} else {
	$('#display').append(`\n<script type="text/babel" src="scripts/gallery_views.js"></script>`);
	$('#likes').append(`\n<script type="text/babel" src="scripts/gallery_likes.js"></script>`);
    // #display returns HTML, but #likes returns "undefined"
	console.log($('#display').html() + " " + $('#likes').html());
}

$(document).ready(() => {
	updatePageTitle();
	displayInstructions();
	toggleContainerLargeAlignment();
	toggleLikes();
	toggleFeedbackLinkHTML();
});

I have no idea why this is happening and cannot fix it. Can someone help me figure this one out?

Thanks

when the script loads #likes doesn’t exist yet, so it is undefined

place your script right before the </body> closing tag

Thanks! That was a very simple solution that I forgot about, and when I applied it, everything worked as it should, because I should have figured that

didn’t exist yet while the first script was running

	<div id="gallery_views_handler"></div>
	<div id="gallery_likes_handler"></div>
	<script src="scripts/gallery_init.js"></script>

Or put all your code inside the document ready method callback. That is what it is there for.


The most common options are:

  1. Put the script in the head and use the defer or async attribute.

  2. Put the script after the page content, usually before the closing body tag.

  3. Put the script anywhere in the document and wrap all the code in an event or async callback. In plain JS, it would be the load or DOMContentLoaded events.

  4. The jQuery equivalence is most commonly just $() with a handler inside that contains all the code. When the handler/callback runs, you are guaranteed that the DOM is ready.

.ready()

jQuery offers several ways to attach a function that will run when the DOM is ready. All of the following syntaxes are equivalent:

$( handler )
$( document ).ready( handler )
$( "document" ).ready( handler )
$( "img" ).ready( handler )
$().ready( handler )