Using JavaScript (without jQuery), modify the target of an anchor link based on its text content

I am working with c# code that dynamically generates Anchor tags. I am looking to modify the target attribute of certain anchor tags based on their text.

For example, the HTML code generated by the dynamic c# looks like this:

<a target='_blank' class=txt href="http://www.stackoverflow.com">THE BEST SITE</a>

I would like to change the target attribute if the text is equal to "THE BEST SITE".

Please note: I do not have any jQuery files included in my asp.net project.

So far, I have attempted to include this script in order to get the text, but it does not display the alert message:

$(document).ready(function() {
    $(".txt").click(function() {
        alert($(this).text());
    });
});

Answer №1

Check out this handy function that verifies whether the innerText of an element matches a specific phrase. If it does, it assigns the target attribute to that particular phrase.

 function updateTarget(element, phrase){
       if(element.innerText === phrase){
         element.target = phrase;
       }
    }

Depending on the structure of your DOM, you can simply loop through all anchor elements and apply this function with the desired phrase.

If you have multiple elements with the .txt class, you can easily handle them like so:

var elements = document.querySelectorAll('.txt');
for(var j = 0; j < elements.length; j++){
  updateTarget(elements[j], "THE GREATEST SITE");
}

Answer №2

You may be looking for a solution similar to this:

let elements = document.querySelectorAll('.txt');
elements.forEach(element => {
  if (element.textContent === "THE BEST SITE") {
    element.target = '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

What causes a component to not update when it is connected to an Array using v-model?

Array1 https://i.stack.imgur.com/cY0XR.jpg Array are both connected to the same Array variable using v-model. However, when changes are made to Array1, Array2 does not update. Why is this happening? Process: Upon examining the logs, it can be observed th ...

Choosing an option from a PHP MySQL table based on a JavaScript value

I am attempting to create a select box that displays a value based on whether the database has a "yes" or "no" in the specified column. Despite my efforts, I am unable to identify any syntax errors causing this code snippet to not function properly. JavaSc ...

Create a new canvas for each iteration of a Vue.JS template loop

I'm having trouble figuring out how to initialize a local "signaturePad" canvas for each loop or required signature. Additionally, I am interested in binding "dataURL" to signaturePad.toDataURL("image/jpg"). This means displaying the dataURI for ever ...

What is the process for making changes to a document in Mongoose?

My goal is to allow users to update existing mongoose documents using a form with method-override package. Despite trying various solutions found on Stackoverflow, I have not been able to resolve my issue. The desired functionality is for the user to view ...

Is it possible to generate an array of objects, where each object includes an observable retrieved through forkJoin?

let food = { id: 1, isTasty: false } Imagine I have a custom function that takes the ID of a food item and returns an observable which resolves to a boolean indicating whether the food is tasty or not. I wish to loop through an array of food items an ...

RxJS Observables trigger the onCompleted function after completing a series of asynchronous actions

I have been attempting to design an observable that generates values from various asynchronous actions, particularly HTTP requests from a Jenkins server, which will notify a subscriber once all the actions are finished. However, it seems like there might b ...

Encounter a 401 error code while attempting to fetch data from CouchDB using an AJAX request

I attempted to make an AJAX call in a JavaScript file to fetch data from CouchDB. Unfortunately, I encountered a 401 error message: Failed to load resource: the server responded with a status of 401 (Unauthorized) This is an extract of my JavaScript cod ...

Saving Labels in Firebase after receiving a POST request for a separate group in Node.js

My system comprises two key collections: posts and tags. The posts collection contains a postId and other relevant metadata, including tags. A typical structure of a post is as follows: { "tags": [ "tag1", "tag2", ... ], ...

The Axios GET Request does not work when inside a while loop

Executing node index.js with this particular code snippet functions correctly. The process entails retrieving a random coordinate using the randomGeo function and then converting it to an address through an Axios call. Subsequently, the transPredtoJSON fun ...

Creating a Website for Compatibility with NoScript

During my journey of building a nameplate site from the ground up for myself, I have delved into the realms of learning and establishing my online presence. The highlight of my project is a sleek tabbed site that employs AJAX and anchor navigation to seaml ...

Refresh the input data post verification

I am just getting started with Vue. I am curious to know if it is possible to automatically update the input value after performing custom validation in Vuelidate. For example, I have an input field for a postcode and I would like to format it correctly i ...

The Bootstrap carousel spiraled into disarray

I am facing an issue with the basic bootstrap carousel. My goal is to make the slides move every four seconds. The current setup of the carousel code is as follows: $(document).ready(function() { fixCarousel(); }); function fixCarousel() { $('.c ...

Auto-scrolling text box cursor movement

My query is quite similar to the topic discussed in this thread on automatic newline in textarea. However, my situation involves multiple textareas with a 1-row attribute, making it seem like writing on air due to the absence of visible borders (I've ...

AngularJS - development of a service entity

After deliberating between posting in the Angular mailing list or seeking assistance from the JavaScript community, I have decided that this is more of a JavaScript question. Hopefully, the knowledgeable individuals on Stack Overflow can provide a quicker ...

Obtain personalized results for implementing in Convase JS from a PHP server

I have a table on my WordPress site with the following output: { { [line1]=> array(3) {{'x'=>'5' , 'y'=>'8},{'x'=>'5' , 'y'=>'8},{'x'=>'5' , &apos ...

Unable to activate animation within a nested ngRepeat loop

I'm struggling to understand how to initiate animations within a nested ngRepeat using Angular. The CSS class ".test" is supposed to be animated. However, when I apply ".test" on the inner ngRepeat, it doesn't seem to work (Plunker): <div ng ...

Is it possible to include two of these on a single page with unique variables? (Using JQuery)

I am looking to create two similar pages, each with different percentages. However, when I try modifying the JS or changing class/ID names, it keeps pulling data from the first SPAN element. http://jsfiddle.net/K62Ra/ <div class="container"> <di ...

What methods can I utilize to expand the qix color library with personalized manipulation features?

Utilizing the qix color library, my goal is to create specific custom manipulation functions for use in a theme. The approach I am taking looks something like this: import Color from 'color'; const primary = Color.rgb(34, 150, 168); const get ...

Restrict User File Uploads in PHP

I have a system set up that enables users to upload files under 200 MB. Once the file is downloaded once, it will be automatically deleted. Additionally, all files are deleted from the server after 24 hours. I am looking for a way to limit the number of up ...

Issue with positioning in expanded state of the Packery isotope pack

Currently working on a website utilizing isotope packery with combination filters and an expanded state upon click. Additionally, the thumbs are sorted randomly upon page load. Encountering an issue where unfiltered thumbs return to their 'name' ...