Remove any URLs and replace them with a text corresponding to the ID of the selected link

I need assistance with a JavaScript code. I have three links, each with a different ID. What I am trying to achieve is that when I click on one of these links, the script should grab the ID, delete all three links, and replace them with text in their place. For example:

<div id="main">     
    <div>
    <div id="links">
         <a id="choice1" href="#footer" onclick="createDiv();removeLink();">choice1</a>
         <a id="choice2" href="#footer" onclick="">choice2</a>
         <a id="choice3" href="#footer" onclick="">choice3</a>
   </div>
   </div>
</div>

When choice1 is clicked, all the links should be removed and a text saying "you clicked choice1" should appear, and the same should happen for choice2 but display "you clicked choice2".

I already have some JavaScript functions created - one to generate a div element with the text and another to remove the links. However, I am unsure how to extract the IDs and display the corresponding text.

function createDiv()
{
    var element = document.createElement("div");
    var main = document.getElementById("main");
    main.appendChild(element);
    var text = document.createTextNode("This is the new text");
    element.appendChild(text);  
}
function removeLink()
{
var link = document.getElementById("links");    
    link.parentNode.removeChild(link);
}

I've scoured the internet for a solution but haven't found an effective method yet. If anyone can provide guidance on accomplishing this task, I would greatly appreciate it.

Answer №1

To implement a click listener on the parent container, identified as #links, and verify if a click occurs on one of its links, extracting the InnerHTML and substituting the innerHTML of your #links div.

document.getElementById('links').addEventListener('click',function(event){
  event.preventDefault();
 var target = event.target; 
  if (target.nodeName === 'A'){
      this.innerHTML = 'You clicked on ' + target.innerHTML; 
 }

});
<div id="links">
<a id="id-1" href="google.com">Option 1</a>
<a id="id-2" href="google.com">Option 2</a>
<a id="id-3" href="google.com">Option 3</a>
</div>

Answer №2

Utilizing event listeners, as shown in this solution, is considered a best practice. However, if you insist on using onclick, you can use 'this' to pass it to createDiv. Here's an example of how your code could be structured:

function createDiv(e)
{
    var element = document.createElement("div");
    var main = document.getElementById("main");
    main.appendChild(element);
    var text = document.createTextNode("you clicked on " + e.innerText);
    element.appendChild(text);  
}
function removeLink()
{
var link = document.getElementById("links");    
    link.parentNode.removeChild(link);
}
<div id="main">     
    <div>
    <div id="links">
         <a id="choice1" href="#footer" onclick="createDiv(this);removeLink();">choice1</a>
         <a id="choice2" href="#footer" onclick="createDiv(this);removeLink();">choice2</a>
         <a id="choice3" href="#footer" onclick="createDiv(this);removeLink();">choice3</a>
   </div>
   </div>
</div>

The 'on*' events all pass the element where the event took place as an argument.

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

Troubleshooting ASP.NET Ajax Error Code 0

Starting from scratch with asp.net and hoping to incorporate infinite scrolling using jQuery Ajax and ASP.NET MVC. Here's the progress so far: <div id="container"></div> <div id="progress" style="display:none"> <h4>Loading ...

Guide on how to use JavaScript to make an HTML5 input field mandatory

I am facing an issue with setting input fields as required based on radio button selection in a form. Initially, all fields should have required=false, but I'm unable to achieve this. No matter what value I assign to the required attribute, it always ...

Error encountered while attempting to invoke endpoint function

Recently, I was handed a Node.js API documented with swagger for debugging purposes. My task also involves implementing some new features, however, I've encountered some difficulty when it comes to calling the functions that are executed upon hitting ...

What is the method for writing the following line in CSHTML server-side code?

<script> function a(id) { var table = document.getElementById(id); .... } </script> @{ //Is there a way to rewrite the line "var table = document.getElementById(id)" here within the ser ...

Is it possible to instantiate a Backbone view by referencing its string name that is stored within a JavaScript object?

I am currently working on a visual builder that utilizes different views for each component. Each view is defined as shown below: $(function() { var parallaxView = new Backbone.view.extend({ .... }); var parallaxView = new Backbone.view.e ...

Automated resizing for various monitor dimensions in HTML

Is there a way to dynamically adjust the zoom level on an HTML webpage based on the monitor size? For instance, an image that appears large on a laptop screen may look small on a PC monitor. Is there a solution available to scale the picture size as the mo ...

How can I generate a dummy JSON response using Backbone Fetch?

Exploring Backbone and looking for a way to simulate the response of a .fetch() call within a model without using a testing library or connecting to an external service. If the setting in the model is this.options.mock === true, I'd like to use an in ...

Having trouble implementing a custom font family in a React Native Text component

Struggling to integrate a custom font into my react native app, I've gone through various solutions from SO and Google but nothing seems to work. I attempted to inform react native about the font by adding "rnpm": { "assets": [ "./assets/fonts/" ...

Continuously monitor the condition in my function

I'm encountering an issue with my jQuery function where it animates a progress bar from 0 to 100 when it's visible on the screen. The problem arises when the progress bar is not initially visible upon page load, as the animation will never trigge ...

The Google Maps JavaScript API is displaying a map of China instead of the intended location

After multiple attempts, I am still facing an issue with setting up the Google Map on my website. Despite inputting different coordinates, it consistently shows a location in China instead of the intended one. Here is the code snippet that I have been usin ...

Placing the word "repeatedly" in a d3 js tree

I am currently working on building a tree structure and incorporating edge labels. The tree allows nodes to be dynamically added using a plus button that appears when you click on a parent node. One issue arises when adding a new child. (apologies for the ...

Any ideas on how to format a date for jQuery Datepicker?

Currently, I have implemented two different datepickers on my website, but I am interested in switching to jQuery's Datepicker for a more unified solution. Here is the current format that I am sending to our backend API: However, I would prefer to i ...

Tips for creating a high-performing algorithm to locate a specific word within a JSON file

I am in the process of creating a word game that involves users typing letters on a board to form meaningful words. If the typed word matches any word in a JSON file, the user earns a point. I have successfully implemented the basic functionalities of the ...

What could be causing my JavaScript/jQuery code to malfunction when dealing with checkboxes?

My code is supposed to select and disable checkboxes based on which radio button is clicked. For example, when Zero is selected, all checkboxes should be highlighted and disabled, except for the zeroth checkbox. However, this behavior does not consistent ...

What is the process for transferring a JSON data object to the server with JavaScript XMLHttpRequest?

When I attempt to send an XMLHttpRequest to a PHP server, I am encountering difficulties in getting the $_POST or $_REQUEST object to be filled with the data I am sending using JavaScript: var r = new XMLHttpRequest; r.open("POST", "http://url.com", true ...

Encountering issues with CSS Modules in Next.JS app while using app/about/layout.tsx

Currently, I am delving into the world of Next.js and encountering some challenges with locally scoped CSS modules. In my project, I have an about directory which contains a layout component. Strangely, the styles applied to the layout component are not b ...

Oops! Before proceeding, make sure to call TestBed.initTestEnvironment() first

Currently, I am experimenting with testing a service in Angular. Below is the code snippet I am working on: describe('AddressService', () => { let service: AddressService; let injector: TestBed; let httpTestingController: HttpTesting ...

how can I enable pass-through functionality in express middleware?

Currently, I have a POST API endpoint named /users which is used to retrieve the list of users. The reason behind using POST instead of GET is because the request body can be quite large and it may not fit in the URL for a GET request. In this scenario, i ...

Using the let keyword from another component within the main React application: Helpful tips and tricks

I'm new to React and I want to be able to use the formIsValid state from one component in my main App.js file. When formIsValid is false, I want the DeliveryNote component to be visible, but when it changes to true, I want to hide the DeliveryNote com ...

Is there a feature similar to Google/YouTube Insight called "Interactive PNGs"?

Recently, I have been exploring the YouTube Insight feature and I am intrigued by how their chart PNGs are generated. When you view the statistics for a video, the information is presented in interactive PNG images. These images seem to be entirely compos ...