PR

This article explains how to retrieve the text of an image caption using JavaScript and assign it to the Alt attribute (alternative text) (using ChatGPT).

This article explains how to retrieve the text of an image caption using JavaScript and assign it to the Alt attribute (alternative text) (using ChatGPT). Blog Management
This article explains how to retrieve the text of an image caption using JavaScript and assign it to the Alt attribute (alternative text) (using ChatGPT).

Have you ever thought, while developing or managing a website, "Wouldn't it be great if I could specify an Alt attribute (alternative text) at the same time as adding a caption to an image?" Generally, captions are for human users, while Alt attributes are for crawlers (machines like Googlebot). Having both improves user experience and SEO , and can potentially increase website traffic. I've long found this cumbersome, so I created a JavaScript script to address this. Please feel free to use it as a reference.

Sponsored Link

*This website is originally in Japanese. Other languages are automatically translated and may contain errors in scientific names or technical terms.

Solve your WordPress image management challenges! How to set captions and alt attributes in bulk using ChatGPT.

Have you ever thought, "Wouldn't it be great if I could specify the Alt attribute (alternative text) at the same time as adding captions to images on static sites or CMSs like WordPress?"

My blog often features explanations about living creatures, and I frequently include ecological photographs. While WordPress makes it easy to specify image captions in the main part of the editing screen, the Alt attribute must be selected and specified from the sidebar on the right side of the editing screen. When inserting a large number of images, it's difficult to see the content of the Alt attribute at a glance, leading to frequent oversights about whether it's been specified correctly.

Since captions and alt attributes are almost always the same, I was wondering, "Isn't there a plugin that makes them the same?" and started searching for one.

However, I couldn't find a solution, and although I could generate it using JavaScript, I lacked the technical skills at the time, so I left this issue unresolved for a long time. Recently, however, I have seriously studied HTML , CSS , and JavaScript, and with the advancement of generation AI , I have discovered that it can be solved using ChatGPT and JavaScript, so I'm sharing it here.

What are captions and alt attributes? What's the difference between them? Why are both necessary?

First, let me explain why it's necessary (or considered necessary) to specify both the caption and alt attributes.

Captions are primarily used to provide descriptions and supplementary information about images. Their main role is to provide context to the user and aid in understanding.

In HTML , captions are usually

It is placed inside another element, and that element is used within that other element.

On the other hand, the original purpose of the Alt attribute is to provide alternative text in case the image is read aloud or cannot be displayed.

The original function of the Alt attribute was to provide alternative information for an image when the image itself cannot be displayed (Craven, 2006), but it is also used to help visually impaired people understand images through sound (Bigham et al., 2010).

The Alt attribute in HTML It is specified as an "attribute" of the element.

The HTML source code has the following structure:

sample
sample

However, this alone might not explain why it's necessary to specify both the caption and alt attributes.

This is because the content of the Alt attribute is now used as part of search engine optimization ( SEO ) and is considered to potentially influence search results.

Search engines like Google Search use crawlers such as Googlebot to programmatically collect information from the web. Research has shown that Google Search uses these crawlers to reference Alt attributes, which are then reflected in the search results (Ferraz, 2015).

On the other hand, captions are not considered to have much of an impact and are seen as playing a role in improving the user experience by making it easier for site visitors to read articles.

In short, in modern times, captions are for the user (human) who is viewing the content, while alt attributes are for crawlers (machines like Googlebot) that are roaming the site.

In other words, by specifying the Alt attribute, image search sites such as Google Image Search may be able to display your website's images more accurately.

Therefore, it is generally considered beneficial to specify both options. It also contributes to improved accessibility.

However, there are many uncertainties about whether crawlers actually ignore captions, and I haven't seen any articles that verify this, so personally, I can't say for sure that the Alt attribute has any influence.

Furthermore, as of the time of the aforementioned paper, it was found that Yahoo!, Bing , and DuckDuckGo do not refer to the Alt attribute (Ferraz, 2015).

How to implement JavaScript in WordPress

However, if there's even the slightest impact, it's preferable to specify both options with minimal effort.

Unfortunately, my knowledge of JavaScript's DOM (Document Object Model) is still limited, making it difficult to write the code from scratch. Therefore, I decided to create it while making modifications along with ChatGPT 3.5.

The following code was obtained:

var images = document.querySelectorAll('figure img');
images.forEach(function (img) {
  if (!img.alt) {
    var figcaption = img.parentElement.querySelector('figcaption');
    if (figcaption) {
      img.alt = figcaption.textContent || figcaption.innerText;
    }
  }
});

The content is surprisingly simple, so I think it's highly versatile.

In Japanese, the following operations are being performed:

  1. This function retrieves all img elements from all figure ` elements on the page. The retrieved elements are stored in the images variable as a NodeList object.
  2. The forEach method is used on the images variable to execute the specified function for each element.
  3. The code performs branching processing if the Alt attribute is not present for each img element.
  4. parentElement and querySelector methods are used on the img element to obtain the figcaption element, which is the parent element of the `<img>` element, and the first element found within it is stored in the figcaption variable.
  5. This process is executed if figcaption variable exists.
  6. The Alt attribute of img element is set to the text content of the figcaption element. If textContent exists, it is used; otherwise, innerText is used. This is because some browsers only support one of them.

In the case of WordPress, you can make this script work by going to "Appearance" → "Theme File Editor" in the menu bar on the left side of the editing screen, and pasting it into "javascript.js" under the heading "Theme Files".

Note that if you are using a CMS (Content Management System) such as WordPress, the HTML code will be enormous, so the id attribute containing the main content will be as follows:

It's faster to limit the processing to items included in the specified category.

There are two types of selectors: querySelectorAll() and getElementById() . However, when specifying a single ID , using getElementById() is faster.

Furthermore, the following code uses document.addEventListener method to wait until the document is fully loaded before executing the script.

document.addEventListener('DOMContentLoaded', function () {
  var main = document.getElementById('main');
  if (main) {
    var images = main.querySelectorAll('figure img');
    images.forEach(function (img) {
      if (!img.alt) {
        var figcaption = img.parentElement.querySelector('figcaption');
        if (figcaption) {
          img.alt = figcaption.textContent || figcaption.innerText;
        }
      }
    });
  }
});

How can I check if the Alt attribute is specified correctly?

Whether the Alt attribute is specified correctly is...Google Search ConsoleYou can find out by checking.

Please note that in order to use Google Search Console, you need to register your website's URL in advance and ensure that your published articles have been crawled.

If registered, paste the URL of the article you want to check into the search form labeled "Inspect all URLs in ~" and perform the search.

After searching, clicking on "Crawled Pages" on the displayed page will show the HTML recognized by Googlebot on the right side.

Click once within the code on the right, then press Ctrl + F on your keyboard to open the search box. Searching for "alt=" in this box will allow you to see the alt attribute specification for the image.

If the above script is working correctly, text should be added to the alt attribute.

What are the advantages and disadvantages of this method?

One of the advantages of this method is, of course, that when you enter text in the image caption, the alt attribute is automatically assigned, just as intended.

As of version 6.4.2, WordPress automatically inserts the "Title" property of the image when you add it using the visual editor. Therefore, if you specify a title in the property, it should be possible to automatically fill in everything. However, I haven't done this because I use this property for a different purpose.

Another side effect I noticed was that I developed the habit of properly adding text to image captions.

Up until now, I often carelessly pasted images onto my sites, thinking, "If there's an image, visitors will understand, and adding captions is a hassle, so it's fine." However, now that I know there's also the benefit of improved SEO , I've developed the habit of entering information much more seriously and accurately.

I don't think there are any major drawbacks, but because it dynamically generates content using JavaScript, if the crawler doesn't execute the JavaScript or the execution is too slow, it might not be able to recognize it properly, and therefore the specification might not be successful. Be careful if your site is heavy due to heavy use of JavaScript.

The script above prioritizes the Alt attribute if one is already entered, so even if you later want to change the caption and Alt attribute to different content, it will be reflected without any problems. Therefore, if you want to specify the Alt attribute individually, specify it from the right sidebar of the visual editor as described above.

If you find entering Alt attributes tedious, you should definitely give this a try!

References

Bigham, JP, Brudvik, JT, & Zhang, B. (2010). Accessibility by demonstration: enabling end users to guide developers to web accessibility solutions. In A. Barreto, & VL Hanson (Eds.), Proceedings of the 12th international ACM SIGACCESS conference on Computers and accessibility (pp. 35-42). Association for Computing Machinery. ISBN : 9781605588810, https://doi.org/10.1145/1878803.1878812

Craven, TC (2006). Some Features of “Alt” Texts Associated with Images in Web Pages. Information Research: An International Electronic Journal , 11 (2), 250. ISSN : 1368-1613, https://informationr.net/ir/11-2/paper250.html

Ferraz, R. (2015). Exploring web attributes related to image accessibility and their impact on search engine indexing. Procedia Computer Dcience , 67 , 171-184. https://doi.org/10.1016/j.procs.2015.09.261

Copied title and URL