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

When should one close a custom-built jQuery dropdown menu?

I created a simple dropdown using a <div> (parent), <span> (current selection), and <ul> (options) which is functioning properly. Now, I'm looking to enhance it by implementing a feature that allows the dropdown to close when the use ...

Learn the process of dynamically updating the source of an HTML5 video

Currently, I am working on a project that involves dynamically loading multiple videos onto a webpage. The structure of my HTML is quite straightforward - it consists of a single video tag. <video controls preload width="520" height="350" id="video"> ...

Use JavaScript to input array elements into a selection of cells in Excel

At this moment, the loop I am executing successfully retrieves the necessary values. However, I am facing challenges when it comes to inserting these array values into a range of cells. I keep encountering the following error message: Error message: "The ...

The updating of input and output does not happen instantly; there is a delay before changes

Having an issue with updating input values in React. When using the setState method, the console log does not show the updated input value immediately. For instance, typing "a n" into the input only logs "a" after the second keystroke... Although I under ...

Adding Options on the Fly

I am struggling with integrating option elements into optgroups within my HTML structure using JavaScript, particularly while utilizing the jQuery Mobile framework. Below is the initial HTML setup: <form> <div class="ui-field-contain"> ...

Utilize Next JS pages api to generate dynamic routes based on unique ids

In the content of my website, there is a collection of objects named stories that are displayed as an array. Additionally, I have a section where each individual story is showcased in detail. I intend to enable users to click on any story link within the ...

Utilizing the closest method to retrieve the form element

As I review code written by another developer, I came across a surprising method used to retrieve a form object. HTML for Login Form <form id="frm_login" action=""> <input type="text" name="username" id="username"> <input type="passwor ...

Utilize AngularJS to loop through a list with ng-repeat

Seeking guidance as an Angular newbie. The ng-repeat in question is formatted as: ng-repeat="f in drillDownList['D' + d.merchMetrics.DEPT_NBR + 'CG' + d.merchMetrics.CATG_GRP_NBR + 'C' + d.merchMetrics.DEPT_CATG_NBR] M ...

Is there a way to create a function that is able to return both a value and a promise

Assume I need to fetch a value only if an object is already present in my model. Otherwise, I should retrieve the output of an endpoint service: model.getDoohkyById = function( id ){ if( this.data ) { if( this.data.length > 0) { ...

Troubleshooting a Vue 2 component's prop receiving an incorrect value

I'm currently working on creating a menu that navigates between categories. When a category has a sub-category, it should return a boolean value indicating whether it has a sub-category or not. <template> <select><slot></slot ...

I can't see the presence of spin.js on my website

I am completely new to Javascript and I'm trying to implement a loading spinner on my website. Whenever users tap the screen, it takes some time to navigate to the desired URL, so we need a spinner to prevent them from tapping repeatedly. I decided t ...

Struggling to effectively transfer a callback function within a series of functions

I am currently utilizing the codebird library to make requests to the Twitter API. The responses from these requests are functioning as expected, but I am looking to pass that response along to my route. Below is a segment of my route.js: router.get(&apos ...

Redux repeatedly triggers re-rendering despite the absence of any changes in the state

This is my first venture into React-Redux projects. I was under the impression that React only re-renders when a component's state changes. However, I am currently facing confusion. The component is being re-rendered every 1 to 3 seconds even thoug ...

Browsing through items within arrays to evaluate their values

I am facing an issue with two arrays that consist of objects. The first array contains restaurant objects with attributes such as name and averagePrice, while the second array has price objects (cheap, medium, expensive) with properties like label, lowEnd, ...

Utilize JavaScript to target the specific CSS class

Hello, I am currently using inline JS in my Wordpress navigation menu, redirecting users to a login page when clicked. However, I have been advised to use a regular menu item with a specific class and then target that class with JS instead. Despite searchi ...

What is the best way to navigate through a complex array in React that includes objects and nested arrays?

I have been working on a JavaScript array that includes subobjects with arrays nested in them. My goal is to iterate through the entire parent object using React. Although I attempted the following approach, unfortunately it did not yield the desired outco ...

Why is my code executing twice rather than just once?

` import './App.css'; import ArrayState from './components/ArrayState'; import FetchApi from './components/FetchAPI/FetchApi'; import Login from './components/Login'; import Useeffect2 from './components/Use ...

JavaScript class name modifications are not functioning as expected

Testing a sprite sheet on a small web page I created. The code for each sprite in sprites.css is structured like this... .a320_0 { top: 0px; left: 0px; width: 60px; height: 64px; background: url("images/sprites.png") no-repeat -787 ...

JavaScript client side event that references the sender object ID in an aspx file

Can someone provide assistance with an issue in the code block below? function(s, e) { form1.hfRaiseEvent.value = s.ID; } This particular function is triggered when the Client Side Click Event occurs. From my understanding, s refers to the Sender Obj ...

Can you explain the process of variable allocation?

I have a query regarding the following JavaScript code snippet. It might be a basic question, but I'm seeking clarification. // 'response' contains JSON data received from the backend: ....then(response => { this.myVar = response.data; ...