DEV Community

Cover image for 5 Must Know JavaScript DOM Methods 🔀
Dom (dcode)
Dom (dcode)

Posted on

5 Must Know JavaScript DOM Methods 🔀

I'm a proud advocate for vanilla JavaScript - I think it's the best way to build an exceptional understanding of the most popular programming language in the world 🌍

If you're into web development, part of being proficient in JavaScript is knowing some handy DOM methods - so here is 5 which you probably didn't know 🤫

1. closest()

Starting us off is my favourite DOM method, closest(). This one is called on a child element, and will traverse up the DOM tree until it finds an ancestor that matches the given selector.

/*
    Example HTML 👇
    ------------------------------------------------
    <ul>
        <li>
            <strong class="myStrong">Nested</strong>
        </li>
        <li>Another list item ...</li>
    </ul>
*/

const myStrong = document.getElementById("myStrong");
const containingList = myStrong.closest("ul");

// containingList == <ul>
Enter fullscreen mode Exit fullscreen mode

One of the best use cases for this method is when you've attached onto an event listener but you're unsure of where you are in the DOM tree, and need to find a parent element ⬆️

2. append()

It's time to stop using appendChild().

The append() method allows you to append multiple things at once - and, it's not just elements. You can also append text at the same time.

/*
    Example HTML 👇
    ------------------------------------------------
    <ul id="myList">
        <li>Apple</li>
        <li>Banana</li>
        <li>Carrot</li>
    </ul>
*/

const myList = document.getElementById("myList");
const pearListItem = document.createElement("li");
const lettuceListItem = document.createElement("li");

pearListItem.textContent = "Pear";
lettuceListItem.textContent = "Lettuce";

myList.append(pearListItem, lettuceListItem);
Enter fullscreen mode Exit fullscreen mode

Also note - the append method is part of the DOM manipulation convenience methods family ➕

3. insertAdjacentHTML()

Another one of my favourites is insertAdjacentHTML() - this one is similar to innerHTML in that it allows you to add HTML directly, but this one works on a relative basis.

You pass in the HTML you wish to add, and a position of where to add it which is relative to the element you call it on.

The available positions are:

  • afterbegin: first element
  • beforebegin: before the parent element
  • beforeend: last element
  • afterend: after the parent element
/*
    Example HTML 👇
    ------------------------------------------------
    <button id="submitBtn">
        <span>Submit Form</span>
    </button>
*/

const submitBtn = document.getElementById("submitBtn");
const iconHtml = "<span class="icon">tick</span>";

submitBtn.insertAdjacentHTML("afterbegin", iconHtml);

/*
    Updated "submitBtn":
    <button id="submitBtn">
        <span class="icon">tick</span>
        <span>Submit Form</span>
    </button>
*/
Enter fullscreen mode Exit fullscreen mode

As you can tell, this comes in handy when building user interfaces and when you need to build elements dynamically 💪

4. matches()

If you're always using event listeners, you're going to love this one.

The matches() method will return true if the element you call it on matches the given query selector 😎

/*
    Example HTML 👇
    ------------------------------------------------
    <button id="myButton">Click Me</button>
*/

const myButton = document.getElementById("myButton");

myButton.addEventListener("click", () => {
    if (myButton.matches(".has-errors")) {
        alert("You have errors!");
    }
});
Enter fullscreen mode Exit fullscreen mode

Useful if you're inside an event listener.

5. replaceWith()

If you find yourself in a situation where you need to update the DOM with new data from the back-end, this method might be perfect.

The replaceWith() method lets you replace an element with one or more others - just like the append() method covered earlier.

/*
    Example HTML 👇
    ------------------------------------------------
    <ul id="myList">
        <li>Red</li>
        <li class="purple">Purple</li>
    </ul>
*/

const purpleLi = document.querySelector(".purple");
const greenLi = document.createElement("li");
const blueLi = document.createElement("li");

greenLi.textContent = "Green";
blueLi.textContent = "Blue";

purpleLi.replaceWith(greenLi, blueLi);

/*
    Result HTML 👇
    ------------------------------------------------
    <ul id="myList">
        <li>Red</li>
        <li>Green</li>
        <li>Blue</li>
    </ul>
*/
Enter fullscreen mode Exit fullscreen mode

JavaScript DOM Crash Course

You can find a complete course on the JavaScript DOM which goes over some of the topics covered in this post at the link below 👇
https://www.udemy.com/course/the-ultimate-javascript-dom-crash-course/?referralCode=DC343E5C8ED163F337E1

Course Thumbnail

Enjoy! 😎

Top comments (4)

Collapse
 
artydev profile image
artydev

Great Thank you :-)

In Closest example there is a little mistake

    <ul>
        <li>
            <strong class="myStrong">Nested</strong>
        </li>
        <li>Another list item ...</li>
    </ul>
Enter fullscreen mode Exit fullscreen mode
<script>
   const myStrong = document.querySelector(".myStrong");
   const containingList = myStrong.closest("ul");
   console.log(containingList)
</script>
Enter fullscreen mode Exit fullscreen mode

Regards

Collapse
 
mjcoder profile image
Mohammad Javed

Awesome examples, thank you.

Collapse
 
jeremymoorecom profile image
Jeremy Moore

Rock on! very useful

Collapse
 
linkkent96 profile image
linkkent96

Helpful, I've never used these DOM methods before!