The function correctly identifies the image source without error

I possess a pair of images:

<img id="img1" src="l1.jpg" usemap="#lb" height="400" border="0" width="300">
<img src="images.jpg" id="img2">

Next up is some JavaScript:

function validateImages () {
    if (document.getElementById('img2').src=="images.jpg") 
    { 
        if (document.getElementById('img1').src=="l1.jpg")
        { 
            window.alert("hello");
        }
    } else { 
        window.alert("goodbye");
    }
}
validateImages();

Furthermore, there is a button that triggers the function:

<button type="button" onclick="validateImages()">Click Here!</button>

Despite both images having their sources set as defined in the script, it continues to display 'goodbye' instead of 'hello'. What could be causing this issue?

Answer №1

The href attribute gives back an absolute URL, for example

<a href="website.html" id="link" />

<script>

    link.href; // http://example.com/website.html

    link.getAttribute('href'); // website.html

</script>

Simply put, you should utilize getAttribute to fetch the value of the href attribute, rather than the property which provides the complete URL

function checkLink() {

    var link1 = document.getElementById('link1');
    var link2 = document.getElementById('link2');

    if (link2.getAttribute('href') == "page.html") {

        if (link1.getAttribute('href') == "about.html") {

            window.alert("hello");

        } else {

            window.alert("goodbye");
        }
    }
}

checkLink();

Answer №2

To ensure that your button functions correctly, consider using the hasattribute method instead of the getattribute function for comparison.

<script>
        imgOne = document.getElementById("img1");
        imgTwo = document.getElementById("img2");
        
        function checkImages() {
            if (imgOne.hasAttribute("src") == "img/1.jpg") {
                if (imgTwo.hasAttribute("src") == "img/2.jpg") {
                    alert("Hello");
                }
            } else {
                alert("Bye");
            }
        }
    </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

Utilizing JavaScript and jQuery libraries in conjunction with periods

I am a bit puzzled about when to include the period before referencing class names. For instance, in this code snippet, why is a period included before the first use of the 'active-slide' class but not for the other two instances? var primary = ...

unable to retrieve the chosen item from the dropdown menu

How can I retrieve the value of the selected item from a dropdown menu without getting an undefined error? You can find my code on Jsfiddle. Can anyone spot what might be causing this issue? <select class="ddl_status" id="status_ddl_20" style="display ...

Refreshing the webpage with new data using jQuery after an AJAX request is

I'm experiencing a problem where the DOM is not updating until after the completion of the $.each loop. On my website, I have several div elements that are supposed to turn orange as they are being looped over. However, once the data is sent to the s ...

Generating a fresh instance from a pre-existing object using JavaScript

Currently, I am facing a challenge from devchallenges.io known as the Shoppingify challenge. After carefully reviewing the prompt, I started working on creating a model that should have a specific format when a request is submitted. { "user": 1 ...

Make sure the "Treat labels as text" option is set to true when creating a chart in a Google spreadsheet using a script

I am currently working on a script using Google Spreadsheet Apps Script interface and I need to set the marker for 'Treat labels as text' to true. Despite searching through App Script documentation, I couldn't find any specific mention of t ...

Executing a protractor test on Safari results in the message "Angular was not located on the webpage https://angularjs.org/"

Recently, I encountered an issue while trying to run a Protractor test on Safari, even when following the official example provided at http://www.protractortest.org/. Below are my conf.js and todo-spec.js files. The problem arises when I set browser.ignor ...

It's possible for anyone to enhance the appearance of the Download button by adding styles without compromising its functionality

Looking to enhance the style of the Download button as it appears too formal. Seeking assistance in adding some button styles to make it more stylish. The code is correct, just aiming to give the Download button a trendy look with specified styles. ...

Uploading files with ExpressJS and AngularJS via a RESTful API

I'm a beginner when it comes to AngularJS and Node.js. My goal is to incorporate file (.pdf, .jpg, .doc) upload functionality using the REST API, AngularJS, and Express.js. Although I've looked at Use NodeJS to upload file in an API call for gu ...

Tips for attaching a load event to an image

Although I am aware that $('img').load(function(){}) can function properly, I am interested in having the img dom that has not been initially created also be able to trigger the event. I am curious as to why the following code snippet does not wo ...

Vue.js - when it comes to rounding off digits, I keep getting unexpected results

Currently, I am in the process of calculating my totals and I need to ensure that they are fixed to 2 decimal places. Here is a snippet of my code: this.selectedCompaniesDetails.forEach((company) => { if(company.id == p.compa ...

Alternative image loading in a figure element

I'm currently in the process of putting together an image gallery using Angular 4.3.0, where images are displayed as background images within figure elements rather than img tags. The images are initially resized to smaller dimensions before being use ...

Discover the process of utilizing doc.getElementbyClassName to determine if any of its elements are blank

On my HTML invoice table, I sometimes have empty elements that cause the row to misalign. To fix this, I want to add whitespace if an element is empty. Here is the structure of the table: <div class="invoiceTable"> <div class="titles2" style=" ...

Transferring a zipped file between a Node.js server and a Node.js client

I am facing an issue with sending a zip file from a node.js server to a node.js client. The problem is that when I try to save the zip file, it becomes corrupted and cannot be opened. To create and send the zip file to the client, I am using the adm-zip l ...

Saving the author of a message from one function and transferring it to another

I'm currently working on a Discord bot that manages tickets as applications. I've almost completed it, but I want the bot to log the closed ticket when the -close command is used. I've experimented with different approaches, such as using a ...

Evaluating string combinations in JavaScript using valid comparisons

After choosing values on the screen, two variables store their value. var uval = '100'; var eval = '5'; There are 2 combinations with values: let combination1= 'u:100;e:1,4,5,10' let combination2 = 'u:1000;e:120,400,500, ...

The Mean stack application is throwing an error message: "user.comparePassword is not

This section contains my user models in the file named "user.js". var mongoose = require('mongoose'); var bcrypt = require('bcryptjs'); let emailLengthChecker = (email) => { if (!email) { return false; } else { if (emai ...

Could someone assist me in identifying the error or mistake?

For my project, I have implemented client and server sign-in & sign-up functionalities. However, after fetching the register API from the frontend, it is displaying an error message "please fill all fields" even though I have provided validation for al ...

The placement of the React.js/Next.js Loader is incorrect on the page

While I was trying to display a Loader over everything during data fetching from my API, I encountered a situation where the Loader was not appearing at the expected top level but inside the page itself. Even though the HTML tree showed it at the top level ...

V-Calendar is not displaying the accurate dates

https://i.stack.imgur.com/zk4h7.png The image displays dates starting on June 1, 2022, which should be a Wednesday but appears as a Sunday on the calendar. This issue affects all months as they start on a Sunday instead of their respective weekdays. The p ...

React ensures that the page is not rerendered until after data has been fetched

I am dealing with the following code snippet. This is my React hook: const [isLoading, setIsLoading] = React.useState(true); useEffect(() => { setIsLoading(() => true); // I expect the page to rerender and display loading now. const select ...