What is the method for obtaining the image alt attribute using JavaScript?

I can't seem to retrieve the image alt tag using JavaScript. Is it even possible and if so, how should I go about it?

Perhaps something like this: $caption.text( flkty.selectedElement ).attr('alt') (last line of JavaScript)

But I'm struggling to make it work...

Thanks!

var $carousel = $('.carousel').flickity({
  imagesLoaded: true,
  percentPosition: false
});

var $caption = $('.caption');
// Flickity instance
var flkty = $carousel.data('flickity');

$carousel.on( 'select.flickity', function() {
  // set image caption using img's alt
  $caption.text( flkty.selectedElement.alt )
});
.carousel-cell {
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.carousel-cell img {
  max-width: 100%;
}

p {
  text-align: center;
}
<link rel="stylesheet" href="https://unpkg.com/flickity@2/dist/flickity.min.css">

<div class="carousel">
  <div class="carousel-cell>
    <img src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/82/orange-tree.jpg"  alt="orange tree" />
  </div>
  <div class="carousel-cell">
    <img src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/82/submerged.jpg" alt="submerged" />
   </div>
</div>
<p class="caption"> </p>


<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://unpkg.com/flickity@2/dist/flickity.pkgd.min.js"></script>

Answer №1

Here is a code snippet demonstrating the use of the attr method:

const img = document.getElementById('image')

const alt = img.getAttribute('alt')

console.log(alt)
<img id="image" src="https://picsum.photos/200/300" alt="this it the alt attribute" />

If you prefer using jQuery, you can achieve the same result with the following code:

const alt = jQuery("#image").attr('alt')

console.log(alt)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img id="image" src="https://picsum.photos/200/300" alt="this it the alt attribute" />

Please note that there is a minor issue in the provided code snippet below:

var $carousel = $('.carousel').flickity({
  imagesLoaded: true,
  percentPosition: false
});

var $caption = $('.caption');
// Flickity instance
var flkty = $carousel.data('flickity');

$carousel.on('select.flickity', function() {
  // set image caption using img's alt
  $caption.text($(flkty.selectedElement).find('img').attr('alt'))
});
.carousel-cell {
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.carousel-cell img {
  max-width: 100%;
}

p {
  text-align: center;
}
<link rel="stylesheet" href="https://unpkg.com/flickity@2/dist/flickity.min.css">

<div class="carousel">
  <div class="carousel-cell">
    <img src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/82/orange-tree.jpg" alt="orange tree" />
  </div>
  <div class="carousel-cell">
    <img src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/82/submerged.jpg" alt="submerged" />
  </div>
</div>
<p class="caption">&nbsp;</p>


<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://unpkg.com/flickity@2/dist/flickity.pkgd.min.js"></script>

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

Add a sublime project with a specific directory path

Currently, I am using Sublime Text 2 for a project that is structured as follows: public vendors a.css b.css myfile.less myfile.css (compiled) I am facing an issue where I need to exclude the css files from the main 'public' folder (specifi ...

Automatically adjust sizes with div elements

How can I automatically resize this iframe within a div? My current method is not effective. <iframe src="http://www.gamepuma.com/external.html?http://data.gamepuma.com/games/06/crash-bandicoot.swf" width="600" height="400" frameborder="0" margin ...

Insert a new HTML element only if it is not already present

<p id="main_class"> <span class="new_class"></span> </p> In this code snippet, I am attempting to append <span class="new_class"></span> to the element with the id of main_class. If the span element with the class o ...

Compare the array against the keys to filter the object

Currently, I have an object with keys that have multiple values. Additionally, there is an array with a simple key check as follows: ["random", "three"]. My goal is to retrieve the mainData, but only with the object and the data that match the keys in th ...

Unable to find the locally stored directory in the device's file system using Nativescript file-system

While working on creating an audio file, everything seems to be running smoothly as the recording indicator shows no errors. However, once the app generates the directory, I am unable to locate it in the local storage. The code I am using is: var audioFo ...

Error message in React/ Ruby on Rails: Encountered Uncaught TypeError when trying to access properties of undefined (specifically, 'id') while passing down a mapped prop

I have been grappling with this bug for the past few days and haven't found a solid solution yet. My objective is to route to an individual component, [http://localhost:4000/hris/employees/1], and display that specific 'employee' card on a ...

What is the process of including a pre-existing product as nested attributes in Rails invoices?

I've been researching nested attributes in Rails, and I came across a gem called cocoon that seems to meet my needs for distributing forms with nested attributes. It provides all the necessary implementation so far. However, I want to explore adding e ...

React Pagination Component not displaying on User Interface

Implementing pagination in my react application has been a challenge for me. I followed this guide to create the Pagination.js file, but unfortunately, I can't see it reflected on my UI. You can view a screenshot of my application https://i.sstatic.ne ...

How can I prevent webpack from injecting eslint errors into my webpage?

Currently working with the Vue webpack project template and I've noticed that when the development server is running, any errors that occur are automatically injected into my webpage and also shown in the browser console. While I understand that this ...

Unresolved conflict stemming from an HTML closing tag in the index.html file, despite both source and destination files being identical

I am currently facing a challenge while trying to merge my code with the master branch through a pull request. The conflict arises in the src/index.html file, specifically on line 17 which states </html> needs to be corrected to </html>. It&apo ...

Tips on adding TypeScript annotations to an already existing global function

I'm contemplating enhancing an existing project by incorporating TypeScript type annotations. Struggling to supply an external declaration file for a straightforward example: app.ts: /// <reference path="types.d.ts"/> function welcome (person ...

Pass data from JavaScript to PHP using AJAX

Using Leaflet to display a map, I have incorporated ajax into my onEachFeature function in order to retrieve variables to pass to PHP. Here is the code snippet: function onEachFeature(feature, layer) { layer.bindPopup(feature.properties.IDLo); layer. ...

Preventing default events on a jQuery slider: enhance user experience

I'm currently experimenting with the superslides library for my project, and I have been trying to implement custom effects on the animations. This is how I attempted to do it: During the beforeChange event, I want to prevent the event from propa ...

Dynamically extracting JSON values

This question may seem very basic to some, but I am struggling with a specific part in the code snippet below. I am trying to make the 'res.DATA.VALUE[i]' part dynamic by using the 'textCol' variable. My intention is to replace it with ...

Move buttons from one group to another group

I have a task to update a group of buttons with different buttons depending on the initial button chosen. Button1: when clicked, both buttons will be replaced by Button1a and Button1b Button2: when clicked, both buttons will be replaced by Button2a ...

What is the process for configuring a registry for a namespaced package using yarn?

Experimenting with yarn as a substitute for npm has been quite interesting. With npm, we usually rely on both a private sinopia registry and the official repository for some namespaced packages, since sinopia doesn't support namespaces. My .npmrc fi ...

Enhance Your Website with Dynamic Autocomplete Feature Using jQuery and Multiple Input Search Functionality

I am working on a form with three input fields. Here is the HTML structure: Name<input type="text" class="customer_name" name="order[contact][first_name]"/><br/> Email<input type="text" class="customer_email" name="order[contact][email]"/& ...

What is the process for altering fonts in a Chrome OS application?

After extensive research on the Internet, I have been unable to find clear instructions on how to modify the text font in a Chrome OS application. Most search results pertain to adjusting the font for the OS user rather than the developer of the app. My i ...

Is it possible to change the name of a PHP file using the value entered in an input

I am currently in the process of trying to change the name of a file while uploading it using the JQuery uploader. I have made some progress, and here is the crucial part of my UploadHandler.php: protected function handle_file_upload($uploaded_file, $name ...

Fiddler is indicating that my JavaScript file cannot be found, despite the fact that it is present and functioning correctly as anticipated

In Default.aspx, I have added the following line to my javascript file: <script type="text/javascript" src="../../MyFiles/JavaScript/JavaScript.js" ></script> When testing the website using Fiddler, I repeatedly receive a 404 error indicatin ...