Encountering a TypeError while including links with role="button" on a page, causing disruption to the after pseudo element

By incorporating a link that leads to a new webpage or initiates a download, a font awesome icon is automatically included using a combination of JQuery and CSS through the ::after pseudo-element. Additionally, a tooltip appears when hovering over the link, informing users whether it opens a new webpage or triggers a file download.

This functionality was working flawlessly. However, upon adding a link with role="button" like

<a type="button" href="https://twitter.com/" class="btn-floating"><i class="fab fa-twitter"></i></a>
on the same page, the Font Awesome icons disappeared and the tooltips stopped displaying on link hover.

Upon removal of the link with role="button," all other links rendered as expected once again.

Upon inspecting the page, an error message appeared: Uncaught TypeError: $(...).attr(...) is undefined

https://i.sstatic.net/kOkQ0.png

Specifically, the script highlighted the following line: return

$(this).attr("href").match(/\.(pdf|doc|docx|ppt|pptx|xls|xlxs|epub|odt|odp|ods|txt|rtf)$/i);

However, after implementing relevant code in the code snippet, everything seemed to be functioning fine (at least for now)!

I seem to have hit a roadblock. Can anyone shed some light on this issue?

Best regards,

/** Icons JavaScript **/
/** Add new-window and download classes automatically to links **/
$('a[target=_blank]').addClass('new-window');
$("a").filter(function () {
   return $(this).attr("href").match(/\.(pdf|doc|docx|
   ppt|pptx|xls|xlxs|epub|odt|odp|ods|txt|rtf)$/i);
}).addClass('download');

/** Links JavaScript **/
/* Check for links in document */
var links = document.querySelectorAll("a");
/* Create index for download links unique id*/
var downloadIndex = 0;
/* Create index for new window links unique id*/
var newWindowIndex = 0;
/* Check links on page */
for (var linkIndex = 0; linkIndex < links.length; linkIndex++) {
   /* Creating a span to wrap the screen-reader text */
   var srTxtWrapper = document.createElement("span");
   /* Add class .sr-only to screen-reader span */
   srTxtWrapper.classList.add("sr-only");

   if (links[linkIndex].classList.contains("download")) {
      /* Add download attribute */
      links[linkIndex].setAttribute("download", "");
      /* Add unique id to download link */
      links[linkIndex].setAttribute("id", "download-file-" + downloadIndex);
      /* Add title attribute saying download file */
      links[linkIndex].setAttribute("title", "download bestand");
      /* Add data-toggle tooltip data attribute */
      links[linkIndex].setAttribute("data-toggle", "tooltip");
      /* Creating the screen-reader text */
      var srTxt = document.createTextNode("(deze link downloadt een bestand)");
      /* Adding the screen-reader text to the span*/
      srTxtWrapper.appendChild(srTxt);
      links[linkIndex].appendChild(srTxtWrapper);
      /* Increase downloadIndex by one for next download link */
      downloadIndex++;
   }
   else if (links[linkIndex].classList.contains("new-window")) {
      /* Add target _blank attribute for link to open in new window */
      links[linkIndex].setAttribute("target", "_blank");
      /* Add unique id to new window link */
      links[linkIndex].setAttribute("id", "new-window" + newWindowIndex);
      /* Add title attribute saying link opens in new window */
      links[linkIndex].setAttribute("title", "open in nieuw venster/tab");
      /* Add data-toggle tooltip data attribute */
      links[linkIndex].setAttribute("data-toggle", "tooltip");
      /* Creating the screen-reader text */
      var srTxt = document.createTextNode("(deze link opent in een nieuw venster/tab)");
      /* Adding the screen-reader text to the span*/
      srTxtWrapper.appendChild(srTxt);
      links[linkIndex].appendChild(srTxtWrapper);
      /* Increase newWindowIndex by one for next newWindow link */
      newWindowIndex++;
   }
}
/* Font Awesome icons for new-window and download classes links (not in button links) */
a.new-window:not(.button)::after,
a.download:not(.button)::after {
  -webkit-font-smoothing: antialiased;
  display: inline-block;
  font-style: normal;
  font-variant: normal;
  text-rendering: auto;
  line-height: 1;
  font-family: "Font Awesome 6 Free";
  font-weight: 900;
  margin-left: 0.35rem
}

a.new-window:not(.button)::after {
  content: "\f08e"
}

a.download:not(.button)::after {
  content: "\f019"
}

/* button floating */
.btn-floating {
  position: relative;
  z-index: 1;
  display: inline-block;
  padding: 0;
  margin: 10px;
  overflow: hidden;
  vertical-align: middle;
  cursor: pointer;
  border-radius: 50%;
  -webkit-box-shadow: 0 5px 11px 0 rgba(0, 0, 0, 0.18), 0 4px 15px 0 rgba(0, 0, 0, 0.15);
  box-shadow: 0 5px 11px 0 rgba(0, 0, 0, 0.18), 0 4px 15px 0 rgba(0, 0, 0, 0.15);
  -webkit-transition: all .2s ease-in-out;
  transition: all .2s ease-in-out;
  width: 47px;
  height: 47px
}

.btn-floating i {
  font-size: 1.25rem;
  line-height: 47px
}

.btn-floating i {
  display: inline-block;
  width: inherit;
  color: #fff;
  text-align: center
}

.btn-floating:hover {
  -webkit-box-shadow: 0 8px 17px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
  box-shadow: 0 8px 17px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19)
}

.btn-floating:before {
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6c0e0303181f181e0d1c2c58425f425d">[email protected]</a>/dist/js/bootstrap.min.js"></script>
     <link href=" https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/css/all.min.css" rel="stylesheet" />
    <link href="https://cdn.usebootstrap.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" />
    
 <p>Link that opens a webpage in new window/tab: <a href="https://www.d2l.com/" target="_blank" class="new-window"
                  rel="noreferrer noopener">D2L
                  Homepage</a></p>
                  
                  <hr>
                   <p>Link that opens as PDF download: <a
                  href="https://www.d2l.com/wp-content/uploads/2022/03/Video-transcript.pdf" download target="_blank" class="download"
                  rel="noreferrer noopener">Transcript of Inclusive Learning with D2L Brightspace (PDF)</a></p>
                  
                  <hr>
                   <a type="button" href="https://twitter.com/" class="btn-floating"><i class="fab fa-twitter" style="color: blue"></i></a>

Answer №1

After some searching, I stumbled upon the perfect solution:

By switching from using ".attr()" to ".prop()", I was able to resolve the issue at hand. Now, everything is running smoothly without any occurrences of the dreaded error message "TypeError: $(…).attr(…)".

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

Sorting React state with the setState method

Here are two different code snippets that can sort an array of numbers in increasing order. [...arr].sort((a,b) => { return a - b; } arr.sort((a,b) => { return a - b; } Both of these approaches will resul ...

The action is undefined and cannot be read for the property type

Using the React+Redux framework, I encountered an error: https://i.sstatic.net/0yqjl.png During debugging, the server data successfully reached the state, but the action was empty: https://i.sstatic.net/41VgJ.png Highlighted below is a snippet of my co ...

Updating the value of an input field seamlessly without the need to reload the page

I am currently working on implementing AJAX to provide auto-complete suggestions for users as they type. At the moment, I have successfully configured AJAX to display the necessary results for the auto-complete functionality in the 'suggestions' ...

Manipulating the location where a dropdown menu intersects with a button

Is there a way to adjust the drop-down menu positioning so that it aligns with the button on the top right side of the menu pop-up, rather than the top left as it currently does? Below is the code I have borrowed from an example on W3Schools. .dropbtn ...

Variable not defined within loop, result may be affected

As a JavaScript beginner, I'm puzzled about why the first loop result shows an "undefined" variable while the rest include "bottles." The goal is to output a statement from 99 to 1. Below is a snippet of the code: /* * Programming Quiz: 99 Bottle ...

Issues with JavaScript Regular Expressions failing to match patterns

Good morning! I've encountered an issue with a JavaScript regular expression that I can't seem to troubleshoot. My script is making a call to the API provided by , and receiving a JSON response containing monitor statuses. However, this JSON st ...

I am currently facing some issues comprehending how to handle a JSON request in Spring MVC

I am currently studying the Spring MVC showcase that can be downloaded from the STS dashboard. Right now, I am focusing on how Spring MVC maps resources and I'm encountering some difficulty in understanding the following scenario: Here, I have a lin ...

Animate images using mouse vertical movement

Creating websites is just a hobby for me, not something professional. Recently, I came across a beautifully designed website that had some unique features I hadn't seen before, like placing three images in one div (which I researched and learned how t ...

Error in Typescript: Function declarations are not allowed in blocks while in strict mode

When attempting to run a script, I encountered the following error message: Function declarations are not permitted in blocks in strict mode during targeting of the 'ES3' or 'ES5' version. The modules are automatically in strict mode. ...

Using a <button> tag instead of a <div> inside of a <button> is not allowed, as clickable divs are typically frowned upon. What

I'm currently developing a React App that functions as a calendar, allowing users to click on specific days displayed as large squares to view information for that day. For accessibility purposes, I initially considered using <button> elements b ...

AngularJS: Refresh array following the addition of a new item

After saving an object, I am looking to update an array by replacing the conventional push method with a custom function. However, my attempts have not been successful so far. Are there any suggestions on how to rectify this issue? app.controller("produ ...

What is the best way to show the previous month along with the year?

I need help with manipulating a date in my code. I have stored the date Nov. 1, 2020 in the variable fiscalYearStart and want to output Oct. 2020. However, when I wrote a function to achieve this, I encountered an error message: ERROR TypeError: fiscalYear ...

Transform a set of numerical values in a JavaScript array into indexed pairs

Let's say I have an array of numbers presented in this format: [5, 29, 1, 5, 4919, 109, 17] My goal is to transform this array into pairs of numbers based on their index within the array. The desired output would look like this: [[0, 5], [1, 29], [ ...

A step-by-step guide on revealing a complete div upon selection

Can anyone assist me in showing a div with a form inside it whenever a specific option is selected from a tag? Here is the code I currently have: <script type="text/javascript"> $(function() { $('#contactOptionSelect&apo ...

Element 1 is positioned with a CSS top attribute of x% and a height of y%, while Element 2 has a CSS top value of (x+y)%. What is the reason behind the discrepancy in

I am encountering a problem with sizing. Desired Outcome: My goal is to use resizable and draggable functionality along with JavaScript code to position elements on the screen by setting their top, left, height, and width. I aim to resize an element unti ...

Is there a way in JavaScript to launch a link in a new tab and overlay a div on top of the existing content of the page?

Is there any method in JavaScript to open a link in a new tab and add a div element on that page? Let's say I have a page called page1.html which has a div containing a link and two radio buttons "yes" and "no". I want to open the link in a separate t ...

Using jQuery to add an attribute to a span element and display an alert message when

I currently have an HTML table set up as shown below: <table id="list" style="width:100%"> <tr> <th>Firstname</th> <th>Lastname</th> <th>Age</th> </tr> <tr class='thread sele ...

receiving an object as the return value in AngularJS

To access locfrnd in the code snippet below, follow these steps: I have created an Array named PlaceCollection containing 2 elements. place locfrnd, which is an array While I was able to successfully access place, I encountered an error when trying to a ...

Retrieve the Firepad textarea element or the current character being typed

I'm looking to add hashtag functionality to Firepad using jQuery. Is there a way to access the textarea element or the character being typed in the Firepad editor? For example, can I trigger an event when typing '#'? I attempted to use the ...

Is it possible to enclose an image with two <div> tags in a single line?

Can anyone help me with this layout issue I am facing? I have two <div>s wrapping an image in the same row, but for some reason, the right <div> keeps dropping below. I've attempted using float, display:inline-block, and tweaking the styl ...