Assign a class to a dynamically loaded element on a webpage

As I work on developing my website, I am facing an issue that I need help with.

My header is stored in a separate HTML document and it looks like this:

<div class="topnav" id="myTopnav">
<a href="Index.html" id="home"><i class="fa fa-fw fa-home"></i>Home</a>                  
<a href="Drinks.html" id="drinks"><i class="fa fa-fw fa-coffee"></i>Drinks</a>
</div>

On every page, I load the header using this HTML:

<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){ 
$('#content').load("Header.html");
});
</script>
</head>

<header class="head">
<div id="content"></div>
</header>

Currently, I am attempting to dynamically add a class to the "a href" tag to make it active, but I am facing issues. I tried creating another function in the "head" tag:

 <script>
 function addAct() {
 var element = document.getElementById("#home");
 element.classList.add(".active");
 };
 </script>

and then manually calling it in the "head" tag right after loading the header:

 <script>addAct()</script>

Unfortunately, this approach does not seem to work. I have tried various other solutions but have not found one that resolves the issue. Can anyone provide assistance?

Thank you!

Answer №1

Have you attempted utilizing the complete callback in the .load() function?

Here is an example:

$(document).ready(function(){ 
    $('#content').load("Header.html", function(){
       // complete loading
       $('#home').addClass('active')
    });
});

If you are using pure JavaScript, you do not need to include a dot (.) in classList.add('active'). Adding a dot will result in

<div class=".active"></div>

Answer №2

The .load() method operates asynchronously, requiring the utilization of the complete callback in order to apply a class only when the data is available.

Additionally, there are a few corrections to be made:

  1. Change from document.getElementById("#home") to document.getElementById("home")

  2. Change from element.classList.add(".active") to element.classList.add("active")

The revised code snippet is as follows:

$('#content').load("https://gist.githubusercontent.com/gaetanoma/7b7ad4592c2b69e14b7cbe0c888ef1be/raw/3cbf59473c5f55a1db5a29f51498f3e9d6739e9b/Header.html", function() {
    var element = document.getElementById("home");
    element.classList.add("active");
});
.active {
    background-color: yellow;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">

<header class="head">
    <div id="content"></div>
</header>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Newbie inquiry regarding the setup and utilization of Bootstrap

I'm currently working on building a website and I decided to incorporate a bootstrap carousel. Initially, I had a dropdown button in the navbar along with a collapsible menu for smaller viewports which were functioning properly. However, when I added ...

Three.js - implementing a billboard effect that preserves orientation through camera pans

My situation involves a plane geometry that always faces the camera using the following line of code in the update loop: plane.lookAt(camera.position); While I am utilizing OrbitControls to manipulate the camera, the plane successfully maintains its orie ...

The Challenge of Implementing Jquery in Internet Explorer

Having troubles with Jquery in IE, the code is not working. Can anyone assist me? Please check this on IE and FF (or opera, safari, chrome), select a state, and you'll notice that clubs load but do not appear in IE while they show up in FF. Your hel ...

Ways to identify which arrays within an object contain an element

This question is unique as it pertains to objects of arrays rather than arrays of objects. I am working with a data structure like the one below and my goal is to determine if any of the arrays inside the object have values. What I'm looking for is a ...

transmit information in real-time using a $.ajax function

In my MVC web site project, I am utilizing jquery. There is a basic C# controller named 'testController' in my project: public class testController { public string test(string id) { return id; } } I also have a javascript f ...

The issue with negative margin-right is not functioning as expected on Chrome's browser

Hello everyone! I'm having some trouble cropping an image using another div. I've noticed that the margin properties -left, -top, and -bottom are working fine, but for some reason the margin-right isn't cooperating on Chrome. Do you have any ...

Do you need to finish the Subject when implementing the takeUntil approach to unsubscribing from Observables?

In order to prevent memory leaks in my Angular application, I make sure to unsubscribe from Observables using the following established pattern: unsubscribe = new Subject(); ngOnInit() { this.myService.getStuff() .pipe(takeUntil(this.unsubscr ...

Embed fashion and graph elements into a CSV document (generated from <script>)

Encountering an issue with my code. I am looking to export an HTML table to a CSV file (specifically Libre Office Calc, regardless of csv, xls or xlsx format, as long as it runs on a Linux Server). Found a script online that works well after some modificat ...

Guide to setting up value observation in React Context for optimal functionality

Imagine a scenario where there is a Parent Component that provides a Context containing a Store Object. This Store holds a value and a function to update this value. class Store { // value // function updateValue() {} } const Parent = () => { const ...

Two identical Vue component instances

Is there a way to duplicate a Vue component instance after mounting it with new DOM? I am currently working on coding a template builder and I need to clone some blocks. Similar to the duplicate feature on this website ...

Struggling with getting the Bootstrap Carousel to switch between slides?

I'm facing a challenge in creating a functioning carousel with Bootstrap. I've utilized a template for this purpose, but the issue lies in the slides not transitioning correctly when I click the arrow buttons to move to the next or previous slide ...

Reposition div when clicked

I have encountered a challenge where I am unable to perform a small task. My goal is to have the position of "div1" change upon clicking on "div2", taking into account that "div2" is nested inside "div1". Additionally, when clicking on "div2" again, "div1" ...

Patience is key as we wait for the webpage to finish loading

I've been searching for a solution to this issue for quite some time without any success... On my webpage, I have a square texture as the background which is set to repeat in order to fill the entire page. However, when a user first enters my site, t ...

Tips on displaying the menu only when scrolling through the webpage

Currently, my website has a right menu that causes overlap with the content on mobile and small devices. To address this issue, I am working on hiding the right menu when the page is stable. The plan is for the menu to appear as soon as the user starts sc ...

Utilizing unique background images tailored to different screen resolutions

In order to enhance the user experience on my website, I am looking to implement a feature that dynamically changes the background images based on the user's screen resolution. My plan is to use a small snippet of JavaScript within the <head> s ...

What is the best way to invoke the datepicker function on all rows of table data that share the 'datepicker' class?

Hey there! I'm working with a table that features a JavaScript function for a datepicker, as well as the ability to add and delete rows. The challenge I'm facing is that each new row created has the same ID as the previous one. How can I ensure t ...

What is the process for utilizing jQuery and ajax to retrieve data from a MySQL database?

I am currently working on a form that includes a "select" box. The goal is to display the relevant records from the database on the same page once an option is selected. This process involves two files: an HTML page containing the form: <form id="theF ...

Ways to have a dropdown menu automatically close when opening another dropdown

Having an issue with managing multiple href links on a single page. When one link is clicked, it opens a dropdown, but if another link is clicked without closing the first one, the first dropdown remains open. How can I resolve this? I initially attempted ...

Exploring TypeScript: Understanding how to define Object types with variable properties names

Having an issue with a React + TypeScript challenge that isn't causing my app to crash, but I still want to resolve this lingering doubt! It's more of a query than a problem! My goal is to set the property names of an object dynamically using va ...

Conceal certain components when a user is authenticated

Below is the content of my app.component.html: <nav class="navbar navbar-expand-lg navbar-light bg-light"> <div class='container'> <ul class="nav navbar-nav"> <li class='nav-item'> <a clas ...