Retrieve the initial link value in jQuery and make changes to it

Is there a way in jQuery to append to the current value of an attribute without storing it in a variable first? For example:

$(document).ready(function() {
  $("#btn").click(function() {
    // get the link currently
    var linkCurrent = $("#link").attr("href");
    // update link
    $("#link").attr("href", linkCurrent + "/added");
    // show the link
    $("#newLink").text($("#link").attr("href"));
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="www.google.com" id="link">Link to google</a>
<input type="button" value="Click me many times and look at new link" id="btn">
<p id="newLink">new link</p>

Something similar to the code above, but I am curious if jQuery provides a way to automatically append to the current attribute value without the need to store it in a variable first.

Answer №1

To implement this functionality, you can utilize the .attr( attributeName, function ) method with a callback as demonstrated below

$('#link').attr('href', function(i, oldHref) {
    return oldHref + '/added';
});

$("#btn").click(function() {
  $('#link').attr('href', function(i, oldHref) {
    return oldHref + '/added';
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="www.google.com" id="link">Link to google</a>
<input type="button" value="Click me many times and look at new link" id="btn">
<p id="newLink">new link</p>

The callback function takes the index and the current value of the attribute(href in this situation). The value returned from the function is used to update the attribute's value.

Answer №2

$(document).ready(function() {
  $("#btn").click(function() {
    // update link
    $("#link").attr("href", $("#link").attr("href") + "/added");
    // show the link
    $("#newLink").text($("#link").attr("href"));
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="www.google.com" id="link">Link to google</a>
<input type="button" value="Click me many times and look at new link" id="btn">
<p id="newLink">new link</p>

There is no requirement to save it in a variable if you are simply appending it. Feel free to use it directly without storing it first.
Using a variable is optional. Variables are typically used to simplify code and avoid repeating the same information.

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

Encountering an error saying "Cannot read property 'x' of null when using Google Charts LineChart"

When I hover over the legend labels on my Google chart, I keep getting an error message that says "Cannot read property 'x' of null," and I'm not sure why. The data is all in JSON format from an AJAX GET request and does not contain any nul ...

Guide to making a reusable AJAX function in JavaScript

Currently, I'm working on developing a function that utilizes AJAX to call data from another server and then processes the returned data using a callback. My goal is to be able to make multiple calls to different URLs and use the distinct responses in ...

Sort by user identifier

I'm having an issue trying to filter a list of posts and comments by userId. I've passed the userId params as postCreator and commentCreator, but something seems to be amiss. Can anyone help me identify what I might be doing wrong? // Defining ...

unable to modify background color when mouse hovers in CSS

Recently, I implemented this code to style the navigation bar on my website. However, I encountered an issue where the color does not change when hovering over the links. .nav { list-style-type:none; margin:0; padding:0; overflow:hidden; } ...

Exploring the Power of Nuxt's asyncData Feature for Handling Multiple Requests

Within my application, there is a seller page showcasing products listed by the specific seller. Utilizing asyncData to retrieve all necessary data for this page has been beneficial in terms of SEO. asyncData ({params, app, error }) { return app.$axi ...

Different ways to modify the style of a MenuItem component in PrimeNG

Seeking advice on customizing the look of a MenuItem in PrimeNG. Here's what I have attempted so far: <p-menu [style]="{'width': '400px'}" #menuOpcoesLista popup="popup" [model]="opcoesListaCS" appendTo="body"></p-menu> ...

Utilizing Angular and Express for routing with the seamless integration of html5mode

I'm facing an issue with making angular and express routing work together with html5mode enabled. When I change state from '/' to my admins state, everything works fine until I refresh the page. Then I only get a json result of admins but my ...

What is the best way to convert every database field into a public variable in PHP?

After running the query below, I have retrieved all database fields: "SHOW COLUMNS FROM admin" Now I am curious about how to convert each field into a public variable within a class structure since I am working with object-oriented PHP. My first step i ...

Access control using Vue.js Cookies

Within my current project, we have both superusers and staff members. The specific task of deleting users is reserved for the superuser role only. This leads me to question whether it is plausible to delete a user by utilizing cookies? ...

What is the best way to position divs on opposite ends around another div?

I have experimented with this scenario so far, http://jsfiddle.net/BXSJe/4/ My goal is to position two divs on the left and right sides within another div, using float:left and float:right resulted in them appearing on separate lines. What I envision is ...

How can I dynamically pass a background:url using JavaScript to CSS?

I have a CSS code snippet below that I would like to dynamically change the "background:url" part using Javascript. div{ background: url('pinkFlower.jpg') no-repeat fixed; -webkit-background-size: cover; -moz-background-size: cover; ...

CSS: Adjusting the vertical alignment of numbers in an ordered list

Hey there, I have a question about the vertical alignment of numbering in an ordered list. It seems that the numbers are being pushed to the baseline when <li> elements contain floated divs only. Is there any way to prevent this and have the numbers ...

What are some alternative solutions when functional component props, state, or store are not being updated within a function?

Initially, I need to outline the goal. In React frontend, I display data that aligns with database rows and allow users to perform CRUD operations on them. However, in addition to actual database rows, I include dummy rows in the JSON sent to the frontend ...

unable to call the anonymous inline onclick method of JavaScript

In my HTML file, I have the following code: <a onclick="getRestaurantTime({{ $afternoonTiming[$j]->id}});">Hello</a> Furthermore, I have an anonymous function in restaurant.js file: var Restaurant = (function ($) { function getRestaur ...

Bootstrap form validation solution

Utilizing bootstrap validation to validate a jsp page. The folder structure is as follows: WebContent ├── bootstrap-form-validation ├── js └── pages All three folders are under the web content. If I create another folder called teacher ...

Checking the active or inactive status using either jQuery or AngularJS

Active or Inactive Status Upon clicking the status, a confirmation box with "Yes" or "No" options will appear. If "Yes" or "No" is not selected and the Esc button is pressed, the value will automatically change from active to inactive. This may require re ...

Top recommendation for utilizing $scope variables in Angular applications

Currently, I am working on a new project and I want to ensure that I am correctly utilizing $scope. After watching an informative video on best practices, Miško mentioned that manipulating $scope properties directly may not be the best approach. Typical ...

Utilizing AJAX to define the attributes of an object

As a beginner in OOP, I am trying to create an object using an ajax request. My goal is to retrieve 'responseArray' in JSON format and then manipulate it. function address(adres) { this.address_string = adres; var self = this; $.ajax({ typ ...

The shopping cart in our e-commerce website is refreshed in real-time thanks to the integration of J

I am currently enhancing the Codeigniter Cart with JQuery by making an Ajax call for updates. Below is my JQuery function: $(function() { $('.cart_form select').on('change', function(ev) { var rowid = $(this).attr('c ...

Unable to integrate an if/else statement into the JSON reply

Working with an API to retrieve data and display images from it. I am attempting to implement an if/else statement that will show photos if the search term yields results in the response, and display a message indicating no results if it does not. Curren ...