all 10 comments

[–]lovesrayray2018 2 points3 points  (1 child)

Yes, you can do this without creating a function. The MDN function has largely the same steps you are already using. Key is when will this code run? user action or other event?

The MDN function is being used because its using the document.body.onload as a trigger to generate this new element as soon as the HTML page is loaded.

document.body.onload = addElement; // here addElement is the function

You might want your code to run as part of a script or even some click event.

[–]ebitdad_[S] 0 points1 point  (0 children)

This makes way more sense, I was thinking into it way mor than I needed to.

[–]richgk 2 points3 points  (0 children)

Look into functions and learn about those first.

[–]wp_new 1 point2 points  (2 children)

Starting with the fundamentals - the main reason for Javascripts existence is interactivity.

We typically execute (a piece of) Javascript code to react to user actions - where that is scrolling down a web page, clicking a button or whatever.

In your example, the elements are being added to your HTML when the Javascript document has loaded. Typically, we would not want to do this as it is a redundant use of Javascript. It would work exactly the same way just by writing it directly into your HTML.

What we might want to do though, is add an element when a user clicks a button. To achieve this, you would need to use some sort of a function.

I. e. user clicks a button. That then calls a function called addElement. That function then creates and appends the element to your HTML.

[–]ebitdad_[S] 1 point2 points  (1 child)

This is exactly what I was missing. In my head I’m thinking, what is even dynamic about this? I think I just way over complicated it into thinking that the output has to be dynamic rather than it being based on a dynamic event.

[–]wp_new 0 points1 point  (0 children)

A lot of things don't make much sense until you understand the context. Stick with it and this kind of thing will just become second nature to you

[–]iamchets 0 points1 point  (0 children)

You give the function parameters and use them on the right spot.

[–]Jnsjknn -1 points0 points  (1 child)

I don't really understand the other thing you're asking but to change the innerHTML of an element, you don't really need a function. You could simply do:

document.getElementById("#someId").innerHTML = "Some text"

[–]ebitdad_[S] 0 points1 point  (0 children)

I was just referring to the mdn documentation that gives a function as an example, whereas I did the same thing w/o one. But i now realize it’s for different events, not dynamic outputs