Using JavaScript to assign the title property to an <a> tag

I'm currently working on modifying a code snippet that utilizes jQuery to display the "title" attribute in an HTML element using JavaScript:

<a id="photo" href="{%=file.url%}" title="{%=file.name%}" 
download="{%=file.name%}" data-gallery><img src="{%=file.thumbnailUrl%}"></a>

By setting the "title="{%=file.name%}", it outputs the full name of the file (including the image extension - .jpg.)

I attempted to introduce an id, as shown above, and used:

document.getElementById("photo").setAttribute("title", "new title");

However, I wasn't able to get it to work. My goal is to incorporate the following script:

 var title2="{%=file.name%}";
 title = (title2.slice(2, title2.length-4));    

This script aims to remove the first 2 characters and last 4 characters from the file name, and then set it as the new title.

Would anyone be able to provide assistance?

Thank you!: )


<!-- The template to display files available for download -->
<script id="template-download" type="text/x-tmpl">
{% for (var i=0, file; file=o.files[i]; i++) { %}

<td style="padding-left:10px; display: inline-block;" class="template-download fade">
<div align="center" class="thumbnail" class="preview">
{% if (file.thumbnailUrl) { %}

<a id="photo" href="{%=file.url%}" title="{%=file.name%}" 
download="{%=file.name%}" data-gallery><img src="{%=file.thumbnailUrl%}"></a>           

 {% } %} </div>

<p class="name">
{% if (file.url) { %}
<a href="{%=file.url%}"  {%=file.thumbnailUrl?'data-gallery':''%}></a>

{% } %}</p></td>'{% } %}
</script>

I'm providing this information because the < a > tag resides within JavaScript in the body, rather than clean HTML, which may impede the use of document.getElementsById and document.getElementsByName here. I am unsure where to call this ID from. There's a small bug in this JS (') but it appears to be functioning correctly! :)

Answer №1

If you're looking to accomplish a specific task, this code snippet can help you achieve your goal.

   let str = '';
//retrieve the name and store it in the variable 'str' here.
document.getElementsById("photo").title = str.slice(2, str.length-4);//'str' represents the file name.

Alternatively, you can extract all links using the following method:

document.getElementsByName("link")[0].title = str.slice(2, str.length-4);

Ensure that your link includes the name attribute:

<a href="#" name="link" tit......><img src="#"></a>

I hope this information proves helpful!

Answer №2

Would you consider attempting it this way?

let image = "picture.jpg"
let title= image.substr(0, image.indexOf('.')); 
title = title.substr(2,title.length)
document.getElementById("photo").setAttribute("title", title );

Check out the code snippet on JSFiddle

Answer №3

When working with jQuery, as previously mentioned, consider implementing the following approach:

<script>
$(document).ready(function () {
    var str = $('#picture').attr('alt');
    $('#picture').attr('alt',str.slice(2, str.length-4));
});
</script>

Answer №4

Perhaps consider assigning a specific name to your element for easier searching, and then attempt the following:

document.getElementsByName("link")[0].title = "New title";

This may not provide a permanent fix, but if it succeeds, it's possible that certain characters in your title attribute are causing issues. If you encounter any console errors with your current method, please let us know.

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

"Time" for creating a date with just the year or the month and year

I am trying to convert a date string from the format "YYYYMMDD" to a different format using moment.js. Here is the code snippet I am using: import moment from 'moment'; getDateStr(date: string, format){ return moment(date, 'YYYYMMDD&a ...

Playwright failing to execute GraphQL tests due to TypeScript configuration problems

I'm facing an issue with my repo where I am running tests using Playwright against a graphQL URL. Despite configuring the tests, there is an error indicating that the environment variable defining the environment cannot be found. The repository in qu ...

Displaying an array of JSON objects in ReactJS by parsing them

Recently, I've encountered an odd issue with my React App. I am attempting to parse a JSON object that includes arrays of data. The structure of the data looks something like this: {"Place":"San Francisco","Country":"USA", "Author":{"Name":"xyz", "Ti ...

How to Generate Custom Expiry Tokens with Firebase Authentication

Currently utilizing Firebase 3.4.1 for my web application. The default token expiry length is sufficient to keep users logged in, but I am interested in managing the expiry manually. Ideally, I would like the token to expire at the end of each session by ...

Attempting to create a single function that can be utilized with numerous divs that share the same class in jQuery

Currently, I am working on creating a basic jquery gallery viewer. In my code, I have the following structure: <div class="photoset"> <img /> <img /> </div> <div class="photoset"> <img /> <img /> <i ...

Value of type 'string' cannot be assigned to type '{ model: { nodes: []; links: []; }; }'

I am a beginner in TypeScript and I have added types to my project. However, I am encountering an error with one of the types related to the graph: Type 'string' is not assignable to type '{ model: { nodes: []; links: []; }; }'.ts(2322) ...

Success message displayed for Ajax form submission, yet email delivery remains pending

In my PHP code for sending emails, I have a function called "Send to friend" that works perfectly with standard PHP post. This confirms that the sendtomail.php file is functioning correctly as well. /* AJAX Code for Send to Friend */ $(function() { $(&ap ...

The replace method for strings in JavaScript does not function properly on mobile devices

I encountered an issue with the string replace method I implemented on my website. Upon checking the page using the web browser on my Android phone, I noticed that it was not functioning as intended. Here's a snippet of the code: /*The function is ...

the pause in execution before my function redirects to a different route

Currently, I am developing a page using nodeJs with express which is supposed to display a table. However, I encountered an issue with my variable "allMusique" that contains the data for my page. When trying to access it initially, there seems to be an err ...

React-Troubleshooting list items and keys: A comprehensive guide to resolving common issues

I'm facing a challenge with generating unique key ID's for my list items. Even though I thought I had a good understanding of how unique keys function, it seems that I am mistaken. In the code snippet below, using key={index} or key={item} is no ...

What could be the issue with my JSON data stream?

Trying to set up the Fullcalendar JQuery plugin with a JSON feed has been a bit of a challenge. The example provided with the plugin works perfectly, so it seems like there might be an issue with my own feed. Here is the output from the working example JS ...

Struggling to display a collection of items in React

Below is the code snippet : import React, { Component } from 'react'; import axios from 'axios'; import _ from 'lodash'; import Loader from './Loader'; export default class Main extends Component { constructor(p ...

When `focus` is bound to a jQuery event handler, the behavior of the select element becomes erratic on

What causes the odd behavior where users need to click twice on a select-option for it to drop down/up after binding an eventhandler to the focus event using jQuery? $('input, select, textarea').focus(function() { $(this).addClass('input_ ...

If the input is unmounted in react-hook-form, the values from the first form may disappear

My form is divided into two parts: the first part collects firstName, lastName, and profilePhoto, while the second part collects email, password, confirmPassword, etc. However, when the user fills out the first part of the form and clicks "next", the val ...

The concept of position() is often mistaken for a function

I am currently developing a slider and have included the code below: $(document).ready(function() { // MAKE SLIDER WIDTH EQUAL TO ALL SLIDES WIDTH var totalWidth = 0; $('.slide').each(function() { totalWidth = totalWi ...

Tips for limiting users to inputting only alphanumeric characters and excluding special characters in an input field using Angular 8

How can I prevent users from inputting special characters in an input field and only allow alphanumeric values? The code that I have implemented so far does not seem to be working as intended. When a user enters a special character, it still shows up in th ...

Despite receiving a return false from the Ajax verification, the form is still submitted when using onsubmit

I have implemented form verification using ajax to check for duplicate usernames. If a duplicate username is found, the function returns false; otherwise, it returns true. Below is the ajax code: function checkform(){ var username = $("#username").va ...

How can I retrieve the value of a radio button using jQuery

My goal is to retrieve the selected/checked radio button value using the .get function. I believe my code is correct, but the sequence seems to be off. $.get('burgerorder_check.php', function(data) { inputVal = $('input[type ...

Unable to convert the BSON type to a Date in MongoDB

I am currently facing an issue while attempting to filter data stored in MongoDB utilizing parameters from the URL. Whenever I send the request, the server crashes and displays the error message: can't convert from BSON type string to Date I attemp ...

ReactJS form example: utilizing two separate submit buttons to perform distinct actions on the same form

I need to implement two submit buttons in my form. Both buttons should utilize the same inputs and form validation, but trigger different actions. export default function FormWithTwoSubmits() { function handleSubmitTask1(){ } function handleSub ...