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

Make Bootstrap Panel Full Width with Highcharts Data

I am currently working on displaying graphs using the Highcharts library on three televisions. All televisions have a FULL HD resolution of 1920 x 1080. I have one Bootstrap panel containing a graph in the panel-body. <div class="panel panel-blue"> ...

The selected value is not displayed in the Material UI select component

My select component is showing the menu items and allowing me to select them, but it's not displaying the selected value. However, its handle function is functioning correctly because when I choose an item, the value in the database gets updated. Bel ...

Can you explain the syntax for the Javascript tag?

While browsing through some code, I stumbled upon this snippet and found myself puzzled by the not:. Is it a tag of some sort? And if so, are there alternative applications for it? var foo = { not: function(bool) { return !bool; } } I'm curious t ...

I will see the "undefined" entity displayed in the bar chart created using react-chartjs

Using the react-chartjs-2 library, I created a bar chart with the following data: const chartData = { labels: ['Dealer1', 'Dealer2', 'Dealer3', 'Dealer4', 'Dealer5', 'Deal ...

When using classList.replace, it should swap out every instance of the class xxx1yyy with xx

I attempted to swap a class and came across this helpful example here: javascript: replace classList that is inside a conditional Unfortunately, my attempt at modification (shown below) did not work. The use of classList.replace should change all instanc ...

Utilizing graphics within the Atom text editor

Hey, I have a bit of a silly question. I can't seem to figure out why these images aren't showing up on my Atom editor. Can anyone help me with this? <body> <div class="top-container"> <img src="images/clou ...

default choice in dropdown menus

I need to populate my option fields with data retrieved from a database. I encountered an error in the console: Error: [$compile:ctreq] Controller 'select', required by directive 'ngOptions', can't be found! I am confident that t ...

Partial data is being received from the Ajax call

I currently have a textarea and a button on my webpage <textarea id="xxx" class="myTextArea" name="Text1" cols="40" rows="15">@ViewData["translation"]</textarea> <input type="button" id="convert-btn" class="btn btn-primary" value="Convert t ...

What could be causing the month to be undefined in this Javascript date?

var currentDate = new Date(); var currentMonth = currentDate.getMonth(); var monthArray = [ 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'S ...

Issues have been identified with React Native UI components RCTBubblingEventBlock and RCTDirectEventBlock not functioning as expected

In my custom native view within an Ignite project, I am facing a challenge with setting up communication from Objective-C to React Native. While the communication from React Native to iOS works using HTML injection, the reverse direction is not functioning ...

MUI React: The Smallest Date Possible

Is there a way to ensure that the user cannot select a To Date that is earlier than the From Date? Below are my Two Date Pickers, with date formatting done using moment. <DatePicker v ...

Activate the places_changed event in Google Maps by clicking the submit button

I would like to activate my placed_changed function when a submit button is clicked. Here's what I have so far: I've set up a searchbox using google.maps.places.SearchBox, and when I press enter while the search box is in focus, it triggers the e ...

Using React to showcase images retrieved from an API request

I am attempting to display images retrieved from an API call. However, I am encountering the following error: Uncaught Error: Cannot find module '""' When I try without using require, no warning is shown, but nothing gets rendered on the page. ...

The State Hook error "state variable is not defined" arises due to an issue with the state declaration in

function Header() { const [keys, setKeys] = useState([]); //custom addition const first = (e) => { var result = new Map() axios.post('http://localhost:8000/' + query) .then(function(response){ var content ...

Tool tips not displaying when the mouse is moved or hovered over

I have customized the code below to create a multi-line chart with tooltips and make the x-axis ordinal. However, the tooltips are not displaying when I hover over the data points, and I want to show the tooltips only for the data in the variable. https:/ ...

Unable to establish the origin for an element using JavaScript

Currently, I am developing a simple game in JavaScript that includes a grid and various cells. Here is the current look of the game which functions perfectly. However, I am facing an issue with setting the margin to 0 and wanting to center the canvas inste ...

Merging Technology: Integrating Maps into Hybrid Applications

Currently, I am developing a mobile application using React-Native with a main focus on: Map Integration: Partial Success - I have successfully implemented all features mentioned in this link. The remaining task is to display live routing based on curren ...

When attempting to view the PDF file, it appears completely void

After spending countless hours on this task, I'm still not making any progress. My goal is to download a PDF file from my server while currently running the operation on localhost. However, whenever I open the downloaded PDF, all I see is a blank whit ...

Here is a helpful guide on updating dropdown values in real time by retrieving data from an SQL database

This feature allows users to select a package category from a dropdown menu. For example, selecting "Unifi" will display only Unifi packages, while selecting "Streamyx" will show only Streamyx packages. However, if I first select Unifi and then change to S ...

Translating Bootstrap 5 into Angular components for version 13 and above

In Angular, the lack of support for optional host-elements and containerless components means that each component comes with its own div wrapper. However, when designing Bootstrap components, a host-less component (without an extra div) is needed to mainta ...