DEV Community

loading...

Back on track to basic DOM manipulation

Jonathan Cohen
I'm a guy that is used to working with my hands in the labor workforce. Last year I decided to start working with my hands in tech.
・2 min read

So now that we've gone over variable assignments and have also talked about functions and methods, we're now ready to finally put it all together to discuss the DOM manipulation we want to achieve. For the final time, we want to take a phrase that is inputted by the user and have it render onto the page when the user clicks the submit button on the form.

Screen Shot 2021-04-20 at 8.07.30 PM

As we examine the HTML document we can see that our form has an ID of formPhrase. With that knowledge, we can set it to a variable. We can also attach a variable to our div with the id of phrasePlace since we'll be adding HTML within the opening and closing tags.

Screen Shot 2021-04-20 at 8.08.01 PM

Now that we have our form able to be accessed as a variable we can now use methods on the variable that represents a particular HTML element. For this example we will use .addEventListener(). This will let allow javascript to listen out for the appropriate action to perform some sort of work. The action, in this case, being 'submit'. That would be the first argument passed to the method with the second being a callback function.

form.addEventListener("submit", function(event){
  event.preventDefault();
  const phrase = event.target.phrase.value;
  phrasePlace.innerHTML += placePhrase(phrase);
});
Enter fullscreen mode Exit fullscreen mode

Within the blocks is where we would put our code. Above in the example, we have an argument (event) being passed into the callback function and then we're calling a preventDefault method on the event as the first statement in the function. On the submission of a form, it's normal behavior for the page to refresh, but we don't want that in this case. Since we aren't fetching to a database the phrases that we would have rendered would be erased and to avoid all of that we're telling the event to not cause a refresh and instead continue with the function. The next line grabs the phrase from the input field. Finally, using a function that takes the argument of phrase and returns HTML with the actual phrase. This returned HTML will be placed in the div that has an ID of phrasePlace.

Take a breath, that was alot of information. Hopefully, this wordy explanation helped to shed light on what DOM manipulation is. Now practice with different types of event listener keywords and see what you find. The only way to learn is to practice!

Discussion (0)