Home > Enterprise >  Add a Class to an existing div element
Add a Class to an existing div element

Time:09-04

I want to display an icon for the my account section right next to the cart icon (Woocommerce).

In order to do that I would like to add another class with the name "et-account-info" to an existing div id element. The HTML-code looks like this:

<div id="et-top-navigation">
    <nav id="top-menu-nav">…</nav>
    <a href="https://example.com/cart/" >…</a>
    <div id="et_mobile_nav_menu"></div>
</div>

Eventually it should look something like this. The new class should be displayed right below the first a tag.

<div id="et-top-navigation">
    <nav id="top-menu-nav">…</nav>
    <a href="https://example.com/cart/" >…</a>
    <a href="https://example.com/my-account/" >…</a>
    <div id="et_mobile_nav_menu"></div>
</div>

I tried using a Javascript function which did not work at all:

<script>
var element = document.getElementById("et-top-navigation");
element.classList.add("et-account-info");
</script>

Any ideas why this is not working? Or is there a smoother way using php?

CodePudding user response:

I assume you are adding the script in the <head></head> tag. Unfortunatly scripts added like this will run before the rest of the document has been loaded/parsed. You need to tell your code to wait for the DOM to be fully loaded and parsed before checking for the element.

function addClassToElement() {
    var element = document.getElementById("et-top-navigation");
    element.classList.add("et-account-info");
}

// Check if document is already loaded. If so, run the function.
// Otherwise, wait for the DOMContentLoaded event to fire before running it.
if (document.readyState === "complete" || document.readyState === "interactive") {
    addClassToElement();
} else {
    document.addEventListener("DOMContentLoaded", addClassToElement);
}

However, your code is incomplete according to the outcome you are looking for. This will just add a class to the div element with ID et-top-navigation.

Have a go at adding (hint: appending) the new element you are looking to add.

  • Related