How to Write into HTML From External JS File


#1

This very simple straight-forward code

document.getElementById("someID").innerHTML = "whatever";

isn’t being called by this very simple straight-forward HTML

<!DOCTYPE html>
<html>

<head>
	<script src = "whatever.js"></script>
</head>

<body>

<p id = "someID"></p>

</body>
</html>

…URL path is correct – all files are in the same folder – and it’s not a matter of typos, either…but the darned thang won’t run right!!

So can it really be that it’s not possible to inject text from an external JavaScript file???

Thanks (as always!!!) for any insight, good people!


Writing to HTML from External JS, Part II
#4

The document must be populated with content before we initiate any DOM interaction with it.

What does that tell us?


#5

Huh?

In my actual HTML I do have “content” – I’d edited out stuff like <p>Problem One: </p> here so it looks nice and to-the-point. In fact, that exact JavaScript above works just fine as inline JavaScript but doesn’t when in an external .js file.

So how am I supposed to “print” on the screen without document.write()?? :wink:


#6

yes, you do, but this content isn’t loaded yet when you do DOM interaction in JS. A html file reads from top to bottom.


#7

That’s a really good point – thanks – but my code’s still not working (after placing the <script> tags right before the closing </body> tag)…I just can’t figure it out and it’s like I need to scream but have got no mouth!!

Something weird in Chrome’s code inspector:

document.getElementById("someID").innerHTML = "<br>";

shows up as an HTML break tag but

document.getElementById("someID").innerHTML = "Say Something Blast You!!!!!!!!";

is ignored as always!! (And thanks, as always, for all y’all’s continued thoughts!)


#8

what if you attempt jsbin:

http://jsbin.com/mikayaxuxe/edit?html,js,output

jsbin automatically links the JS file and assures DOM is ready. Does your code work there?

if problem persist, could you share the directory with all the files maybe? (use google drive/dropbox), then we can attempt your problem locally to fiddle with the problem


#9

Yeah, not working in JS Bin, either (one of my favorites)…anyway, here’s that Google Drive folder:

https://drive.google.com/open?id=1esx8ic4zqclHW1mU5QNacPBbpSeauyJ4

And here’s a screenshot of Chrome’s inspect functionality showing that only <br> tags get used:

Thanks for the assist…I really should head for bed now: it’s six-thirty in the morning in NYC and I’ve been doing coding related stuff (watching videos, actually coding [and failing at it!], reading books on program design and algorithms [ha!]) since like eight last night! So it’s probably mental fatigue more than anything…hey, would you be even kinder and do me a favor: give me just the barest of a hint but let me figure it out, okay?

THANKS!!!


#10

you can just retrieve the element once, then store it in a variable and use innerHTML, so you don’t have to lookup the element each time:

var first = document.getElementById("first")
first.innerHTML = "something";
first.innerHTML = "<br>";

then the remaining problem is that break will overwrite "something", if you comment out the break insert, you should see "something"

furthermore, DOM manipulation is expensive, so preferable DOM manipulation is done in a single go if possible


#11

As mentioned earlier, cache the page element node so it can be repeatedly accessed. It is a callable object in memory until the end of the session.

const first = document.querySelector('#first')

document.write and innerHTML are old school. The former should never be used on a page that faces the web. The latter is used when the text contains HTML. Today we have node.textContent.

first.textContent = "This will go straight to the screen";

If we wish to grow the text content. then,

first.textContent += "This will also go straight to the screen following the above."

The above could assume a paragraph element which is a content container. However we could append a paragraph that contains the text given that #first is a DIV.

let p = document.createElement('p');
p.textContent = "Text to populate the paragraph";
first.appendChild(p);

We can create the element at the top of the script along with the page element node, and leave it cached. We can repopulate it and append as often as we wish. When working with it in the script it is only in memory, not in the document the way first is.


Aside

In script it is often recommended we use liberal amounts of whitespace, especially surrounding operators.

a = 5 * n

as opposed to,

a=5*n

However, in HTML we generally don’t use a lot of whitespace.

<p id="some-id"></p>

as opposed to,

<p id = "some-id"></p>

or,

<script src = "some-script.js"></script>

Attributes are declarations, and as elements may have several or many attributes, the norm is to only use whitespace to separate them.

<img src="picture.png" width="250" height="200" alt="">

#12

WAIT A MINUTE…I can’t believe this: the implications of your remarks are that JavaScript cannot perform a simple

print("Hello World!")

like in every other language out there???

Not only do I have to do the monstrous

document.getElementById("someID") = "whatever";

but that it can only be done once per ID – so that I can’t keep writing line after line of something unless it’s all in that one command?!?!?!?!

document.getElementById("fourth").innerHTML = "Roses are red,<br>Violets are blue,<br>Pornhub is down,<br>So your mom's Facebook will do!";

And on top of it all, I ought to assign that command to a variable…and even then it’s “expensive” to use JavaScript to write to the screen!!!

So how ever do people output dynamic content onto the screen (the current document in view)???

Wow…thanks for that revelation but I’m just like, WTF…whoa, this is weird…or am I just not understanding something???

  1. don’t use document.write()
  2. use document.getElementById()
  3. but use that sparingly
  4. and as a variable (i.e., as the variable’s assigned value)
  5. and everything (all content) has to “go in a once” (in one go, on that one line/in that one command)
  6. and it’s “expensive” performance-wise

Is that it???

So how do people ever generate dynamic content on the webpage??? Wasn’t that the whole point of JavaScript originally???

Thanks again…wow!!!


#13

Did not know that…all the online resources I’ve looked into use them (when not using console.log)! Thanks for this…

And thanks for the rest of your thoughts…my head’s just all over the floor right now so I’m gonna have to collect it all and re-assemble everything first…

Really, thanks…wow…


#14

Uh, never mind…I see now that Roy, your fellow moderator (wow there are more “chiefs” than “braves” here! Do you guys get paid for this?? I really appreciate all the help these two weeks!!), has provided some guidelines so I’m gonna try digesting them…after I put my exploded brain back together again first…I can’t believe a simple “print-to-screen” command is sooooooooooo convoluted in JavaScript!! Wow, and I thought having to first include a bunch of libraries in C++ for simple basic functions was bad…


#15

this code:

document.getElementById("fourth").innerHTML = "Roses are red,<br>Violets are blue,<br>Pornhub is down,<br>So your mom's Facebook will do!";

isn’t very maintainable, making change its easy to mess something up, difficult to write test for given its just a single string.

well, there are other methods then innerHTML which allow to add multiple elements:

https://developer.mozilla.org/en-US/docs/Web/API/Node/appendChild

so what you can do is create the elements first in JS and then do the appending in a single go:

var div = document.createElement('div');
var paragraph = document.createElement('p');
paragraph.textContent = 'hello world';
div.appendChild(paragraph);
document.body.appendChild(div);

yep, doing DOM manipulation is JS is difficult, which is why there is a whole scala of frameworks (reactJS, vueJS, jquery) to make it easier


#16

What the h3ll?!?! The whole point of JavaScript is DOM manipulation!!

Thanks again for all your instruction – you and Roy both, actually…I’m just flabbergasted here, absolutely flummoxed…it’s like finding out that my wife is cheating on me – with a woman! And that my wife was always a man!!!

Oh my…maybe I should’ve kept going with Python or even C++ instead…sheesh… o_0


#17

well, JS was designed and build in 10 days. And they are not willing to make breaking changes like php (5 -> 7) and python (2 -> 3) did.

browsers where originally never designed for the heavy load we deal with today, they where made for simple static webpages. According to some people, browser are one of the most over engineered pieces of software to deal with a problem they weren’t designed to handle in the first place.

well, c++ is a lot more difficult then JS. JS is just full of quirks.

So yea, its interesting to read the history about the DOM and JS, then you also better understand why its not so easy. And why the JS ecosystem is a mess, new frameworks arise nearly every day or maybe every day. Its astounding. This picture gives you an idea:


Writing to HTML from External JS, Part II
#18

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.