Modifying URL with JavaScript

I'm experimenting with changing the href link in JavaScript. Specifically, I want to switch the URL path from "linktwo.html" to "problem3.html".

While there may be simpler ways to achieve this, I'm using this as a learning exercise.

In my sample code below, what mistake am I making in attempting to alter the href?

HTML:

<body onload="changeLink()">
<div id="p">
<h1><a href="linkone.html">first link</a></h1>
</div>
<div id="q">
<a href="linktwo.html">second link</a>
</div>

Javascript:

<script type="text/javascript">
function changeLink() {
document.getElementById("q").querySelector('a').href = "problem3.html";
}
</script>

Answer №1

Choice A : Modify the JavaScript like this

<script type="text/javascript">
function adjustLink(){
document.getElementById("x").href.innerHTML="<a href="solution4.html"> third link </a>";
}
</script>

Choice B : revise the code as shown below

HTML :

<body onload="adjustLink()">
<div id="y">
<h1> <a id ="y1" href="linkA.html"> first link </a></h1>
</div>
<div id ="x">
<a id ="x1" href="linkB.html"> second link </a>
</div>

JAVA SCRIPT :

<script type="text/javascript">
function adjustLink(){
document.getElementById("x1").removeAttribute("href");
document.getElementById("x1").setAttribute("href","solution4.html");
}
</script>

Answer №2

Kindly review the code below

<script type="text/javascript">
  function modifyURL(){
    document.getElementById("link").href = "challenge3.html";
  }
</script>

Answer №3

To start off, ensure that the ID is placed directly on the link itself and not on the surrounding div.

<a href="page2.html" id="new_link"> click here </a>

Next, make sure to utilize the href attribute exclusively without including the innerHTML property.

function updateLink(){
    document.getElementById("new_link").href = "finalpage.html";
}

Answer №4

What should be the id for the href

</head>
<body onload="changeLink()">
<div id="p">
<h1> <a href="linkone.html"> first link </a></h1>
</div>
<div id ="secondDiv">
<a href="test.html" id="q"> second link </a>
</div>

and eliminate the innerHTML section from the javascript:

<script type="text/javascript">
        function changeLink(){
            document.getElementById("q").href = "problem3.html";
}
</script>

Answer №5

Here is an alternative method:

<a id="newLink" href="linktwo.html"> second link </a>

Assign an id to your anchor tag and then in the script section:

 newLink = document.getElementById('newLink');
    newLink.removeAttribute('href');
    newLink.setAttribute('href','differentPage.html');

Retrieve the element first, remove the current href attribute, and replace it with a new one! I hope this solution addresses your query more effectively.

Answer №6

Appreciate everyone for sharing such valuable insights! After some additional tinkering, I ended up modifying my JavaScript code to the following:

function updateLink(){
document.getElementById("q").childNodes[1].href="problem3.html";

I'm unsure of its practicality, but thought it could be a useful addition to the existing solutions provided.

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

Discovering and editing a specific line in Sheets: An in-depth look at the Message Counter

Currently, the bot checks if your ID already exists in the sheet list and adds you if it doesn't when someone writes a message in the chat. Now, I want the bot to implement a message counter in the sheet list. What would be the most effective way to ...

Utilize jQuery ajax to pull in data from an external website

I've been doing some research on using jQuery ajax to extract links from an external website, but I'm a bit lost on where to begin. I'm taking on this challenge just to push my skills and see what I can accomplish. While reading about the S ...

Tips for utilizing useQuery in React JS class component:

Currently, I'm working on an app that is exclusively built using React JS class components. Since UseQuery only functions with function components and the Query tag has been deprecated, I'm facing some challenges in getting the data I need. Any s ...

React Material-UI is notorious for its sluggish performance

I recently started using React Material-ui for the first time. Whenever I run yarn start in my react app, it takes quite a while (approximately 25 seconds) on my setup with an i5 8400 + 16 GB RAM. Initially, I suspected that the delay might be caused by e ...

What is the proper method for writing this jQuery attribute code in WordPress?

The function in my theme file looks like this: $(document).ready(function() { $(".ajax-loader").attr("src","<?php bloginfo('template_url'); ?>/images/ajax-loader.gif"); }); When executed, the src attribute displays <?php bloginfo(& ...

When using Express, some static files may display raw code instead of rendering the intended HTML content

I am facing an issue with an anchor link in my layout.hbs file. The link is supposed to direct to layout2.hbs, but instead of rendering proper HTML, it displays a page of raw code. Upon checking my console messages, I can see the following: GET / 304 28. ...

Emulating a Linux command line interface within a web browser

Recently, I came across an interesting Linux simulation in a browser created by Fabrice Bellard. Curious about how the Linux emulator in Javascript by Fabrice Bellard actually works? While exploring a website today, I discovered a full Linux terminal sim ...

Error message: "In Jade and Express.js, the attribute req.body.[name of form] is not defined

I am encountering an issue while trying to update a database using a drop-down form. The problem is that req.body.[name of form] is coming up as undefined. Upon checking the console, I found that req.body shows up as an empty object {}. Below is the code ...

Trigger javascript function after clicking on two buttons

I am currently working on developing a web game inspired by Duolingo. In a specific scenario, I need a function to be triggered after two button clicks to progress further. However, I am facing challenges in finding solutions online or understanding it on ...

Enhance the post data in jqGrid by including an extra parameter when inserting a new row through a modal form

When trying to add a new record with a modal form in jqGrid, I am having trouble adding an additional dynamic parameter to the POST data. I attempted: $('#table').setPostData({group: id}); $('#table').setPostDataItem('group' ...

Tips for automatically redirecting a webpage to another webpage upon submission of form elements:

I'm currently working on a website where I want to integrate radio buttons as part of a form. Below is the code snippet I've been using... <form action="glitter.php" method="post"> <input type="radio" name="font" value="fonts/darkcrysta ...

Tips on dividing the information in AngularJS

Sample JS code: $scope.data={"0.19", "C:0.13", "C:0.196|D:0.23"} .filter('formatData', function () { return function (input) { if (input.indexOf(":") != -1) { var output = input .split ...

I'm struggling to connect the output of my Button to my JavaScript function

I have been working on a new feature for my website and encountered an issue with a JavaScript function. The goal is to enable disabled input boxes when the user clicks on a "yes" button. Unfortunately, clicking the "yes" button doesn't seem to be tr ...

Using JavaScript to duplicate records and XML data

I'm in the process of creating a system for user data submissions that will export an XML file, readable by other software. However, I've run into an issue where only information from the first form is being captured when I replicate it for addit ...

Having trouble getting your AJAX call to function properly? Could be that you're searching for the incorrect

Whenever the button is pressed, I need an AJAX call to be sent to my events_controller#check action. Here's the code snippet: events\new.html.erb: <button id="check-button" type="button">Check</button> application.js: $(document). ...

Issue with h2 tag within JQuery's read more feature

How can I modify my jQuery code to wrap the middle text in an h2 tag? I am currently using a code snippet from code-tricks. You can find the original code snippets here: $(document).ready(function() { var showChar = 100; var ellipsestext = "..."; ...

Tips for adjusting border colors based on the current time

Trying to change the border color based on the opening hours. For example, green border from 10am to 9:29pm, yellow from 9:30pm to 9:44pm, and orange from 9:45pm until closing at 10pm. The issue is that the colors change at incorrect times beyond midnight. ...

Utilize Bootstrap accordions nesting inner accordions to create a dynamic user interface with varying shown.bs.c

I am currently dealing with a nested bootstrap accordion issue. The problem arises when I click on the inner accordion - it unexpectedly triggers the 'shown.bs.collapse' event bound to the outer accordion, which is not the intended behavior. Is t ...

Create an array by populating an Object with JS

Could you provide instructions on how to populate this element as an array? testdata = [ { key: "one", y: 200 }, { key: "two", y: 300 } ]; For example: testdata=[]; testdata[]="one"; testdata[]="tw ...

What's preventing me from changing module.exports? Why is my browser suddenly giving me errors after `npm run build` ran smoothly?

How come the browser is preventing me from executing the following code: Getters.js let Getters = {} Getters.foo = function(){ return 1; } Getters.bar = function(){ return 2; } module.exports = Getters; However, after running npm run build and serve -s ...