After updating the INNERHTML, the NAV tag content is no longer functional

I am facing an issue with replacing the contents of a NAV tag that contains UL list items. The original HTML within the NAV tag works perfectly fine, but when I replace it with my own HTML - which matches the original word for word - the dropdown functionality of the NAV stops working. I have meticulously compared every letter and word between the two versions. One thing I did notice is that one of the anchor HREF attributes contains a '#'. Here is the original code inside the NAV:

<nav id="nav">
<ul>
<li class="current"><a href="index.html">Welcome</a></li>
<li class="submenu">
<a href="#">Show Me</a>
<ul>
<li><a href="hybrid/index.html">The Hybrid</a></li>
</ul>
</li>
</ul>
</nav>

My code looks like this:


var pstrHTML = "<ul>"
+ "<li class='current'><a href='index.html'>Welcome</a></li>"
+ "<li class='submenu'>"
+ "<a href='#'>Show Me</a>"
+ "<ul>"
+ "<li><a href='hybrid/index.html'>The Hybrid</a></li>"
+ "</ul>"
+ "</li>"
+ "</ul>";
document.getElementById("nav").innerHTML = pstrHTML;

Although I have added an ONCLICK event with a WINDOW.ALERT to the "Show Me" list item, confirming that the INNERHTML replacement is functioning correctly on page load, the NAV is still not behaving as expected in comparison to the original HTML.

Answer №1

When removing the element, any event bound to it will also be removed.

To ensure the event remains active, you can bind it to the document instead of the specific element using document.AddEventListener(). Then, check if the target contains the id #ShowMe.

document.AddEventListener("click",function(e) {
   if(e.target = "#idOfYourElement"){
      // do something
   }
});

View a working demo below;

document.getElementById("nav").addEventListener("click", function(e) {
  if (e.target = "#ShowMe") {
    alert("Hello World!");
    var pstrHTML = "<ul>" +
      "<li class='current'><a href='index.html'>Welcome</a></li>" +
      "<li class='submenu'>" +
      "<a id='ShowMe' href='#'>Show Me</a>" +
      "<ul>" +
      "<li><a href='hybrid/index.html'>The Hybrid</a></li>" +
      "<li><a href='hybrid/index.html'>New Element 1</a></li>" +
      "<li><a href='hybrid/index.html'>New Element 2</a></li>" +
      "</ul>" +
      "</li>" +
      "</ul>";
    document.getElementById("nav").innerHTML = pstrHTML;
  }
});
<nav id="nav">
  <ul>
    <li class="current"><a href="index.html">Welcome</a></li>
    <li class="submenu">
      <a id="ShowMe" href="#">Show Me</a>
      <ul>
        <li><a href="hybrid/index.html">The Hybrid</a></li>
      </ul>
    </li>
  </ul>
</nav>

document.AddEventListener() is similar to

$(document).on("action","#id",function(){ });
in jQuery.

UPDATE: Included Teemu's answer, which will also work;

document.getElementById("nav").addEventListener("click", function(e) {
  if (e.target = "#ShowMe") {
     // do something
  }
});

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

Font Awesome icons are preventing the navigation bar from collapsing

Just getting started with Bootstrap and facing an issue. I want to include a collapsed user icon that expands when clicked. However, when I add the navbar-toggle class, the icon disappears completely. Without it, the icon appears but doesn't collapse ...

Identifying a particular pattern in a JavaScript string

What is the best way to check if a JavaScript String includes the pattern: "@aRandomString.temp" I need to verify if the String includes an @ character followed by any string and finally ".temp". Thank you ...

How can I make multiple elements change color when hovering with CSS?

Hey there! I have a little design challenge that I need help with. On my website (), I am trying to make multiple elements of a specific item change color when the user hovers over the text. If you hover over the "more" menu item, you'll notice that o ...

Background not covering full height despite setting HTML and body heights to 100%

I've been struggling to set my wrapper to 100% height, despite setting the height to 100%. Any solutions? At the moment, my main_wrapper is empty and should have a background color of red. While I'm looking to add a footer using position: fixed ...

If I dared to eliminate the emphasized line, this code would completely fall apart

<!DOCTYPE html> <html> <head> </head> <body> <h1 id="message-el">Ready to play?</h1> <p id="cards-el"></p> <p id="sum-el"></p> <butto ...

Issue encountered while attempting to load several google charts simultaneously

What do I need? I am in need of two Google charts, one on each tab of the website as shown in the screenshot below: Tabs What seems to be the issue? The second chart is not loading properly and showing mixed information. This can be observed in the scre ...

What is the best way to initially hide a div using slide toggle and then reveal it upon clicking?

Is there a way to initially hide the div tag and then animate it in a slide toggle effect? I attempted using display:none on my '.accordion_box' followed by show() in slideToggle, but this results in adding the CSS property display: block. My goa ...

Initiate an "execute.document" command directly from the address bar

While reviewing my old website, I stumbled upon this snippet: <input type="image" id="QuickPass" name="QuickPass" src="/images/QuickPass.gif" alt="Quick Pass" onclick="document.pressed=this.value" value="QuickPass" /> nestled within this form: & ...

Click the link to capture the ID and store it in a variable

Currently working on a project involving HTML and JavaScript. Two HTML pages ("people.html" and "profile.html") are being used along with one JavaScript file ("people.js") that contains an object with a list of names, each assigned a unique ID: var person ...

What is the best way to ensure the search box remains fixed in the top navigation bar while maintaining a fluid and responsive design?

I've been struggling as a novice programmer, and even with the help of more experienced programmers, we haven't been able to figure it out. I'm trying to integrate a search box into the top navigation that adjusts responsively to different ...

Angular Material (8) error code S2591: The variable 'require' is not defined in the current scope

Currently, I am attempting to record the date and time in the JavaScript console. Despite the code successfully logging the dates, an error message persists: Note: The code is functioning properly, with the dates being displayed in the console. It is only ...

Troubleshooting EasyTabs: Localhost Issue with Ajax Tab Configurations

I've implemented EasyTabs for organizing my tabs on a webpage. I decided to use ajax-tabs functionality in order to fetch content from other pages when users click on the navigation menu buttons. However, I've encountered an issue where the conte ...

A step-by-step guide on masking (proxying) a WebSocket port

Within my server-side rendering React app, I have set up a proxy for all HTTP calls to a different port. Take a look at the code snippet below for the HTTP proxy configuration. import proxy from "express-http-proxy"; const app = express(); const bodyParse ...

Tips for initializing the store in Vue when the application first starts

Seeking assistance in loading products from my pinia store upon the initial load of my Vue app. Check out my app.js below: import {createApp} from "vue"; import App from "./App.vue"; import router from "./Router/index"; impor ...

Animating content through CSS and jQuery to reveal its unfolding effect

Just stumbled upon the amazing quote-expansion animation in the OSX Mail app and I am completely impressed. I am on a mission to bring that same magic to the web (or at least close to it), but unsure if anyone has done something similar yet. A couple of ...

What is the most optimal method for transforming this array of objects into a different format?

My array consists of objects structured like this: [ {prop1: valueA, prop2: valueB, prop3: valueC}, {prop1: valueD, prop2: valueE, prop3: valueF}, ... ] I am looking to transform this array into objects with a different structure: [ {x: valueA, y: value ...

Utilizing jQuery to Calculate Tab Scores

Last week, my teacher and I collaborated on a fun game called rEAndom game (). The game is created using javascript, jQuery, and HTML5. One interesting feature of the game is that when you press the TAB key, a div displaying the score appears. You can chec ...

JQuery form plugin experiencing issues with Ajax functionality

I am facing an issue with implementing the Jquery form plugin using ajax to insert my form data into the database. Although the validation is working correctly, the ajax call is not receiving any data in response. It seems like I might not be following the ...

The function grunt.task.run() is malfunctioning

Currently, I am experimenting with integrating Grunt into my Express application. Here is a snippet of the code I have: var grunt = require('grunt'); require(process.cwd() + '/gruntfile.js')(grunt); grunt.task.run('development&ap ...

Transfer a term to a different division - JavaScript Object Model

I am trying to achieve a specific task where I need to move one term under another in SharePoint. However, despite my efforts using JSOM and SharePoint 2013, I have not been able to find a direct method for moving terms. The code snippet I have used below ...