Rather than writing out all the pseudo-code for you, I talk through it in the video below. Please take the time to write the pseudo-code out first. If you try and just write code, I'm sure you'll miss steps. Pseudo-code can help you spot simple mistakes. Good luck!
// If the element is already on the page:
var el = document.querySelector("img");
el.setAttribute("src", "http://example.com/logo.png");
// If the element is NOT on the page (new el):
var el = document.createElement("img");
el.setAttribute("src", "http://example.com/logo.png");
// If the element is already on the page:
var el = document.querySelector("p");
el.textContent = "The quick brown fox...";
// If the element is NOT on the page (new el):
var el = document.createElement("p");
el.textContent = "The quick brown fox...";
// Let's start with something simple:
var el = document.createElement("li");
el.textContent = "Go grocery shopping...";
var parentEl = document.querySelector("ul");
parentEl.appendChild(el);
// Now, we could move the hard-coded values to variables:
var name = "li";
var text = "Go grocery shopping...";
var parent = "ul";
var el = document.createElement(name);
el.textContent = text;
var parentEl = document.querySelector(parent);
parentEl.appendChild(el);
// That's good, but what we really want is a function.
// Now, we can addElements whenever we want.
function addElement(name, parent, text) {
var el = document.createElement(name);
el.textContent = text;
var parentEl = document.querySelector(parent);
parentEl.appendChild(el);
}
addElement("li", "ul", "Go grocery shopping...");
In that last example, you could imagine now putting that
function in a helpers.js
file and reference
it from any program:
<script> src="helpers.js"></script>