Discovering whether an image contains a caption with the help of JavaScript

There are various websites that display captions on images in paragraphs, h1 tags, or contained within a div along with the image.

I am interested in learning how to determine if an image has an associated caption using JavaScript, especially when the caption is directly on the image and takes up space.

The examples provided below showcase different methods of adding captions to images. Is there a universal way to identify whether a caption exists?

<figure>
  <img src="http://images.all-free-download.com/images/wallpapers_large/small_island_wallpaper_beaches_nature_wallpaper_1388.jpg" alt="Tea cup with steam and pen on bed">
  <figcaption>Journaling with Tea</figcaption>
</figure>

<div class="image">
  <img src="http://images.all-free-download.com/images/wallpapers_large/small_island_wallpaper_beaches_nature_wallpaper_1388.jpg" alt="Tea cup with steam and pen on bed">
  <p>Journaling with Tea</p>
</div>

<!DOCTYPE html>
<html >
<head>
<style type="text/css> 
.imageHolder {
    position: relative;
    width: 285px;
    height: 175px;
}
.imageHolder .caption {
    position: absolute;
    width: 283px;
    height: 50px;
    bottom: 0px;
    left: 0px;
    color: #ffffff;
    background: green;
    text-align: center;
    font-weight: bold;
    opacity: 0.7;
}
</style>
</head>
<body>
<div class="imageHolder">
<img src="http://images.all-free-download.com/images/wallpapers_large/small_island_wallpaper_beaches_nature_wallpaper_1388.jpg" alt="" />
<div class="caption">
<br>Caption goes here
    </div>
</div>
</body>
</html>

Answer №1

if the structure always follows this pattern:

<div class="imageHolder">
        <img src="http://images.all-free-download.com/images/wallpapers_large/small_island_wallpaper_beaches_nature_wallpaper_1388.jpg" alt="" />
        <div class="caption">
            <br>Enter caption here
        </div>
    </div>

perhaps something similar to this format:

function myFunction() {
    var x = document.getElementsByClassName("imageHolder");
    var c = x[0].childNodes;
    return (c[3].className == "caption");
}

Answer №2

Let's take a look at this example:

 <div class="image" id="theImage">   <img
 src="http://images.all-free-download.com/images/wallpapers_large/small_island_wallpaper_beaches_nature_wallpaper_1388.jpg"
 alt="Tea cup with steam and pen on bed">   <p>Journaling with Tea</p>
 </div>

If you are familiar with how the caption is designed, you can easily extract it using the parent and child DOM model.

//get the div/div's
var div = document.getElementById("theImage");
var children = div.children;
for (var i = 0; i < children.length; i++) {
  var child= children[i];
  // Do stuff
  // You can check if it's an image by className
  // If it's a paragraph then get innerTEXT
}

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

No testing detected, ending with code zero - NPM and YARN

After installing node js and yarn, I attempted to run an application/script developed by someone else. However, when running the test, I encountered the following message: No tests found, exiting with code 0 Watch Usage › Press f to run only failed tes ...

Establishing Node.js environment variables when invoking `npm run` command

package.json { "scripts": { "start": "NODE_ENV=development node ./index.js" } } If we wanted to pass and override NODE_ENV when running npm run start, is it possible? npm run start NODE_ENV=production ...

Transform Unicode characters into HTML using Qt

I am facing an issue with a particular string that includes Unicode characters and special symbols. The string, for instance, looks like this: SYMBOLSU+2510\n The string contains the Unicode character U+2510 and a new line symbol \n. I have a lo ...

AJAX forms and snippets

I have successfully integrated comments into public activity following a tutorial on public activity #406 Public Activity. However, I am facing issues with submitting the comments via ajax. I have gone through several tutorials but haven't been able t ...

Adding HTML components to an image with adjustable dimensions

A graphic designer has provided us with an image featuring three selection boxes. I implemented the necessary HTML elements and CSS to display three overlapped selection boxes on top of the image, using pixel values for positioning. However, the original ...

The value retrieved from the event handler function's state does not match the anticipated value

While debugging, I often minimize this particular component to understand its behavior later on. It was quite challenging to pinpoint the issue due to some intricate logic in place. Nonetheless: import { useContext, useEffect, useState } from "react&q ...

Achieving enlightenment with Satori in NextJS: Transforming SVG to PNG in a NodeJS Environment

I am currently exploring the capabilities of satori and integrating it into my next.js api routes. (I'm unable to utilize the vercel/og package). While I have successfully set everything up, I'm facing a challenge in converting the svg image gen ...

How to Use Jquery to Delete a Specific String

I've been attempting to remove certain strings from a string using Jquery, however it seems like the code isn't working and my variable remains unchanged. var classes = $("body").attr('class'); alert('.side-nav' + classes); c ...

Issue with Angular App: Bootstrap navbar not displaying on smaller screens

I am working on an Angular app (using Angular 11.2.4 with Bootstrap 4.5.3) and facing an issue where the navbar is not rendering correctly on screens smaller than ~580 pixels wide. Even when I click the toggler to 'expand' the collapse region, n ...

Mastering the art of maximizing efficiency with the Jquery Chosen Plugin

Currently, I'm facing an issue with the jQuery chosen plugin due to my large datasets causing the select box to hang and slow down. Below is my implementation of the plugin: var request = $.ajax({ method: "POST", url: "ajaxRequest.php", d ...

Unexpected Results from Div Positioning

Here is the PHP code snippet I am working on: <?php include 'header-adminpanel.php'; ?> <div class="container"> <div class="body-content"> <div class="side-left"><?php include 'adminproduct_sidebar.ph ...

ng-if not functioning properly following the activation of the "Save Changes" button

When I click the edit change button, I am updating information and then hiding the form to show the updated details by clicking on the Save Changes button. My API successfully updates the information, but for some reason, ng-if does not seem to work afte ...

Can a jQuery/JavaScript script be run standalone?

I've got a bunch of HTML pages saved on my computer and I'm looking to create a JavaScript script that can extract specific text or elements from those pages. I found some jQuery code snippets on Stack Overflow that do what I need, but I'm n ...

What is the functionality of the getBlock('meta') method within DocPad?

While transitioning a website from a different site generator to DocPad, I am currently exploring the capabilities of the getBlock('meta') feature. Understanding how to utilize getBlock('scripts') and getBlock('styles') was re ...

Unable to scroll to top using div scrollTop() function

Here's the fiddle I mentioned: http://jsfiddle.net/TLkmK/ <div class="test" style="height:100px;width:70px;overflow:auto"> Some text here that needs scrolling. </div> alert($('.test').scrollTop()); Feel free to scroll down ...

Tips for sending textarea data via AJAX with TinyMCE

Recently, I encountered an issue with submitting forms using the TinyMCE Jquery plugin. While regular input fields like text fields and select boxes submit just fine, there seems to be a glitch when it comes to submitting a textarea with TinyMCE. It requir ...

divs aligned at the same vertical position

Struggling for days to align buttons vertically, I have tried various approaches without success. I attempted using position: absolute; bottom: 0; on the parent with position: relative; set. @import url('https://fonts.googleapis.com/css?family=Mon ...

Why is it not possible to declare an interface or type within a TypeScript class?

I am struggling to define interface | type within a TypeScript class. Here is the code snippet: class MyClass { interface IClass { name: string, id: string } } However, I keep encountering this error: Unexpected token. A constructo ...

Activate the parent navigation link when on sub-pages

I want to ensure that the parent navigation item is highlighted when a user is on a child page based on the URL. For example, if the user is currently viewing foo1-child and the parent is foo1, I need to apply the active class to Foo 1: http://foo.com/foo ...

Exploring the fundamentals of Django with a touch of creativity in CSS

As a newcomer to Django, I am currently working on setting up a basic Django application. I have progressed to chapter 5 in the Django online book: Before delving into databases, my goal is to incorporate some simple CSS and JS directly into the applicat ...