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

Angular's FormGroup for reactive forms is a powerful feature that allows for

Why am I unable to type in the input field before setting a value? html <form action="" [formGroup]="titleForm"> <input class="note-title" type="text" formControlName="title"> </form> ...

Can HTML be transferred between browser tabs using Angular?

I'm in the process of developing a unique Angular (v17) application that allows users to drag and drop HTML elements, even across multiple browser tabs. I am inspired by the capabilities demonstrated by neo.mjs, as shown in this demo: https://www.yout ...

Are DOM Events compatible with ajax-loaded content that cannot be unloaded?

How should events be managed with ajax-loaded content that can be hidden or displayed? I have created a sidebar in HTML that toggles visibility on click, along with two pages that are loaded using ajax. When the sidebar is hidden or displayed, I need to ...

Select a single option from the group to include in the array

I'm currently developing a new soccer betting application. My goal is to allow users to choose the result of a match - whether it's a win, loss, or draw - and then save that selection in a list of chosen bets. https://i.stack.imgur.com/hO3uV.png ...

When working with JavaScript and Node.js, it is not possible to access an object's index that is

Utilizing babyparse (PapaParse) in nodejs to convert CSV to JavaScript objects has been quite challenging for me. After processing, the output of one object looks like this: { 'ProductName': 'Nike t-shirt', ProductPrice: '14.9 ...

Is it possible to use mapDispatchToProps in Redux without mapStateToProps?

As I dissect Redux' todo example to gain a deeper understanding, I came across the concept of mapDispatchToProps. This feature allows you to map dispatch actions as props, which led me to consider rewriting addTodo.js by incorporating mapDispatchToPro ...

"Enhance your website with dynamic PHP Ajax live search and infinite scrolling

When scrolling to the bottom of the .dropdown-menu, I would like to load an additional 7 rows from the database. However, I haven't been successful in implementing this feature using the script provided. I am currently utilizing Bootstrap CSS and JS f ...

Steps for achieving uniform positioning of a div element that dynamically appears within a table with two rows and four table data cells

If I want to display the same div in different positions dynamically on my page, how can I achieve that? My page has a table with two rows and two columns, each containing an Embed button. When these buttons are clicked, a div is shown with a list of site ...

Issues with the functionality of jQuery append and AngularJS ng-if not functioning

In my application using checkboxes, I control the visibility of charts with the ng-if directive and implement drag-and-drop functionality with angular-Dragula. The use of ng-if is essential for me as it allows me to manipulate visible div IDs and organize ...

Resolving the Issue of Jerky Graphics During HTML5 Canvas Animation

When animating a layer in canvas, the visual quality becomes uneven if there are additional layers present. You can see an example of this by clicking "RUN" on this fiddle: http://jsfiddle.net/Q97Wn/ If I modify this line: opts.percentageIndicator.clearR ...

Using Vue.js to Authenticate Users with JWT Tokens Sent in Registration Emails

Hey everyone, I could really use some assistance with JWT tokens. I created a registration form using Vue.js and sent the data to the database using axios. Now, I need help figuring out how to save the token I receive in the confirmation email so that I ca ...

Encountering a cannot POST / error while using Express

I am encountering an issue with my RESTful API while using Postman to call the route /websites. Despite my efforts, I keep receiving the error message "Cannot POST /websites". In addition, I am exploring the implementation of a job queue utilizing Express, ...

Building a custom DSL expression parser and rule engine

In the process of developing an app, I have included a unique feature that involves embedding expressions/rules within a configuration yaml file. For instance, users will be able to reference a variable defined in the yaml file using ${variables.name == &a ...

Creating a dynamic circle that expands in size based on the duration the user presses down (using Java Script)

I have a fun challenge for you! I want to create a growing circle on a canvas based on how long you hold your mouse button. Currently, I can draw a fixed width circle where my mouse was when I clicked, but I need it to dynamically change size as you hold t ...

The dichotomy between public and private methods within a Vue.js component

Within a component, I have two functions defined. One is foo(), which is defined within <script>, and the other is fooExported(), which is defined in the body of export default {}. My understanding is that functions inside export default {} can be a ...

Ways to minimize the loading time of contents within the Dropdown

I am facing an issue with the loading time of my dropdown list. When trying to load 100,000 items on button click, it takes too long. Is there any way to reduce the loading time? Looping through Products for (int i = 0; i < 100000; i++) { ...

Unable to input information into Textbox in real-time

Having trouble entering data from one page to another using ng-model. After filling in some information in a textbox and moving to the next page, I want the same data to be entered when I return to the previous page. I've written the code but it doesn ...

Automatically reduce the size of Java Script files and CSS files with compression

I'm currently working with Google App Engine and JQuery. I'm looking for a solution that can automatically compress my JavaScript and CSS files when deploying them to the GAE server. It's quite cumbersome to manually compress all the files e ...

Leverage the version attribute within package.json within one of its scripts

Is there a way to access the version attribute of my package.json file within one of its scripts? I want to include the version number in the name of the JS bundle, instead of using a hash as an identifier. This is what I currently have: "build-js": "bro ...

Assign the value/text of a div element by using JavaScript/jQuery within a PHP loop

I'm struggling to figure out how to set the value/text of a div using javascript/jquery inside a loop. Can anyone offer some guidance on this issue? Goals: Extract data from a database. Use javascript/jquery to assign the extracted data to an eleme ...