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

Is there a way to retrieve the BrowserRouter history from outside of the BrowserRouter component?

Here is a simplified code snippet (using react-router-v5). I am trying to figure out how to access BrowserRouter's history in the logout_Handler() function, even though I am "outside" BrowserRouter. I came across this answer on How to access history ...

ESLint detecting error with returning values in async arrow functions

Currently facing a minor inconvenience instead of a major problem. Here is the code snippet causing the issue: export const getLoginSession = async (req: NextApiRequest): Promise<undefined | User> => { const token = getTokenCookie(req) if (!t ...

Is there a way to customize the color of specific sections on a dygraph chart?

I am looking to incorporate dygraphs into my website, but I need help with displaying a specific background color in certain parts of the chart. For example, I want the chart to show green during daylight hours. Can you assist me in achieving this? ...

Steps for linking a keypress to trigger a specific action

I need help creating a script that will redirect to a URL when a button is clicked. Below is the code I have developed. HTML : <a id="#next" href="example.com">↵</a> <a id="#previous" href="example.com">↳</a> JS : $(document ...

What steps can be taken to enable users to draw a path on a Google Map?

I'm working on a new project for a Facebook app that will allow users to map out their marathon route using Google Maps. I plan to utilize mySQL database records to store fixed points along the path (such as specific locations based on latitude and lo ...

Troubleshooting Event Tracking Problems with Brave Browser on PostHog

After successfully implementing Posthog with React and testing it on Chrome and Firefox, we encountered issues when trying to test it on Brave/Microsoft Edge Browsers. It appears that the default ad blocker feature in these browsers is causing the problem. ...

Is it possible to utilize a computed property for dynamically styling a table row based on certain conditions?

I have a table of users that I am currently rendering, and my goal is to highlight the entire row only for the current user. My initial thought was to use a computed property to achieve this, but I seem to be facing some difficulties in making it work. I ...

The RemoveEventListener function seems to be malfunctioning within Angular2 when implemented with TypeScript

I am currently incorporating three.js into Angular2. The code I am using is quite straightforward, as shown below. this.webGLRenderer.domElement.addEventListener('mousedown', ()=>this.onMouseDown(<MouseEvent>event), false); this.webGLR ...

JavaScript can be used to extract a specific value from a SOAP response

In order to extract the Patient ID (PATAA000000040) from the SOAP response below using JavaScript and insert it into a Mirth destination, we need to target the value under the livingSubjectId tag. It's important to note that this tag may repeat, but w ...

Increase the count for each category with the help of JavaScript

Currently, I am working on an application using PHP and have 180 vendors registered in the database. Each vendor has a unique ID stored in the database. I need to create a system where every time a user clicks on the "view details" button for a specific ...

What is the method to reach a named parameter within a function?

Currently, I am building a RESTful web service using Node JS in combination with Backbone JS. Within this service, there is a specific REST method called GET /users/id/:id, where :id represents the user's identification number. The purpose of this met ...

Guide for executing Gulp tasks in a sequence one by one

Here is an example snippet: gulp.task "coffee", -> gulp.src("src/server/**/*.coffee") .pipe(coffee {bare: true}).on("error",gutil.log) .pipe(gulp.dest "bin") gulp.task "clean",-> gulp.src("bin", {read:false}) .pipe c ...

What is the best way to merge two interfaces and convert all of their fields to optional properties?

I have two unalterable interfaces: interface Person { name: string; age: number; } interface User { username: string; password: string; } I aim to merge them into a single interface called Player // please, adjust this code accordingly interfac ...

Update the HTML weather icon with data from JSON

I have a collection of weather icons stored on my computer. How can I customize the default weather icons with my own set of icons? In the JSON file, there is a variable like this: "icon":"partlycloudy" <html> <head> <script src="http://c ...

Sending an Ajax request using an array of parameters and then accessing them in PHP

I have created a JavaScript function that facilitates AJAX posts by accepting an array of parameters. The function is outlined below: /** * A quick function to execute an AJAX call with POST method and retrieve data in JSON format * @param {string} url - ...

How come useEffect runs only once even when multiple states in the dependency array of useEffect change simultaneously?

<div onClick={() => { updateValue1((x: number) => x + 1); updateValue2((x: number) => x + 3); }} > one? two? </div> const [value1, updateValue1] = useState(1); const [value2, updateValue2] = useState(1 ...

What is the proper method for invoking object (class) methods from a router?

My apologies for the vague title. Let me clarify what I am attempting to accomplish. In this scenario, there are two main components: A class called 'wallet.js' A router named 'index.js' which handles GET requests This is my objectiv ...

Troubleshooting issues with adding child elements in JavaScript

Styling with CSS: ul #allposts li{ height: 50px; width: 50px; background-color: yellow; border: 1px solid yellow; } Creating HTML structure: <ul id = "allposts"></ul> Adding JavaScript functionality: var container = documen ...

Changing the element tag and flipping escape characters in html entities

My control over the string source is limited, as I can only use html(). However, I am in need of cleaning up the chaos within the source, The goal is to remove all instances of <div class="page"></div>, while retaining its content. The challen ...

Is there a way to convert the items in the products variable into the more comprehensive detailedProducts?

New to JS, looking for guidance on transforming the products variable into detailedProducts in JavaScript const products = [ { title: 'Yellow Pail', submitterAvatarUrl: 'images/avatars/daniel.jpg', productImageUrl: 'images ...