0

I'm wondering why my javascript isn't working to append to the end of the docmap div tag? At least I try it in chrome and I don't see it say: "Some new content!" in the docmap div tag.

<html>
<header>
<style>
#docmap {
  background-color: #f0f0f0;
  height: 100%;
  width: 200px;
  position: fixed; 
}
#main {
  margin-left: 200px;
  position: 200px; 
  padding: 20px;
}
</style>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>

<script>
    //alert("hey!");
    var docmap = $("#docmap");
    docmap.append('<br>Some new content!');
</script>
</header>

<body>

<div id="docmap">
<ul>
<li> hello
<li> hi
<li> howdy
</ul>
</div>

<div id="main">
<h1>header1</h1>
<h2>header2 a</h2>
<h2>header2 b</h2>
<h1>header1 a</h1>
</div>

</body>
</html>
pico
  • 1,660
  • 4
  • 22
  • 52
  • 4
    You have your code in the header, the DOM doesn't even exist yet. Either use JQuery DOM ready, or place your script before the body close tag. – Keith Feb 04 '20 at 13:50
  • shouldn't the console report an error if that's the case? – pico Feb 04 '20 at 13:50
  • No, jquery works on collections, if the collection is empty, it just doesn't do anything. – Keith Feb 04 '20 at 13:51
  • 1
    @pico there is no error in this case - you try to find an element using `$("#docmap")` and since it doesn't exist, you get an empty collection. When you try to do anything with it, it's just a no-op. – VLAZ Feb 04 '20 at 13:51
  • Does this answer your question? [Is $(document).ready necessary?](https://stackoverflow.com/questions/4643990/is-document-ready-necessary) – Alon Eitan Feb 04 '20 at 13:52
  • is there a way to wait for the doc to be created and keep the script in the header? – pico Feb 04 '20 at 13:52
  • 1
    @pico yes, using `$(document).ready()` – VLAZ Feb 04 '20 at 13:52
  • @pico why would you want to keep the script in `head`? – aloisdg Feb 04 '20 at 13:58

1 Answers1

1

In the <html> tag, you should use <head>. <header> is a tag for another purpose. Also you must move your script in the bottom on the body after the declaration of the tag you are looking to call with JQuery.

Try it Online! or directly here:

    //alert("hey!");
var docmap = $("#docmap");
docmap.append('<br>Some new content!');
#docmap {
  background-color: #f0f0f0;
  height: 100%;
  width: 200px;
  position: fixed; 
}
#main {
  margin-left: 200px;
  position: 200px; 
  padding: 20px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="docmap">
<ul>
<li> hello
<li> hi
<li> howdy
</ul>
</div>

There is a Q&A about <head> vs <header>: <header> vs. <head>

If you are wondering where to put the <script> tag, well SO has your back:

aloisdg
  • 22,270
  • 6
  • 85
  • 105