Why does my JavaScript code only function properly on the initial div element?

I want to create a JavaScript function that changes the color of the title when I hover over an image. It seems to be working, but only for the first div. Could it be an issue with my scoping?

Thank you!

<body>
    <div>
      <a href="" id="img"><img src="http://www.vetprofessionals.com/catprofessional/images/home-cat.jpg" class="img" width="200"></a>
      <a href="" id="head1"><h1>test title</h1></a>
    </div>
    <div>
      <a href="" id="img"><img src="http://www.vetprofessionals.com/catprofessional/images/home-cat.jpg" class="img" width="200"></a>
      <a href="" id="head1"><h1>test title</h1></a>
    </div>
</body>
<script type="text/javascript">
var image = document.getElementById("img");
var text1 = document.getElementById("head1");

function changeTextRed() {
    text1.style.color = 'red';
};

function changeTextDefault() {
    text1.style.color = 'blue';
};

image.onmouseover = function(){
  changeTextRed()
};

image.onmouseout = function(){
  changeTextDefault()
};

</script>

Answer №1

Avoid using the same IDs for multiple elements as it can cause issues. Instead, utilize classes and access them in JavaScript like this:

var images = document.getElementsByClassName("img");
var headings = document.getElementsByClassName("head1");

Update your HTML to use classes:

<body>
    <div>
      <a href="" class="image"><img src="http://www.example.com/image.jpg" class="img" width="200"></a>
      <a href="" class="title"><h1>Sample Title</h1></a>
    </div>
    <div>
      <a href="" class="image"><img src="http://www.example.com/image.jpg" class="img" width="200"></a>
      <a href="" class="title"><h1>Sample Title</h1></a>
    </div>
</body>

Answer №2

It is recommended to use only CSS for this task.

a h1 {
  color: blue
}
a:hover ~ a h1 {
  color: red
}
    <div>
      <a href="" id="img1"><img src="http://www.vetprofessionals.com/catprofessional/images/home-cat.jpg" class="img" width="200"></a>
      <a href="" id="head1"><h1>test title</h1></a>
    </div>
    <div>
      <a href="" id="img2"><img src="http://www.vetprofessionals.com/catprofessional/images/home-cat.jpg" class="img" width="200"></a>
      <a href="" id="head2"><h1>test title</h1></a>
    </div>

Answer №3

The main purpose of having an ID is to uniquely identify something, whereas for grouping multiple HTML elements, classes are used.

To retrieve an array of all elements with a specific ClassName in JavaScript, you can utilize the following function:

document.getElementsByClassName("ClassName")

After obtaining the elements, you need to iterate through each one to apply your desired functions. There are two straightforward approaches to achieving this.


If you prefer a design where a function is called, here's an example:

var elements = document.getElementsByClassName("ClassName")
for(var i in elements) {
    (function(elem) {
    elem.mouseover = function() {
        elem.style.color = 'green';
    }
    )(elements[i]);
}

Alternatively, you can take advantage of the fact that the scope of the function during a mouseover event is the element itself:

...
function setColor() {
    this.style.color = `green`;
}
for(var i in elements) {
    elements[i].mouseover = setColor;
    elements[i].mouseover = function() {
        setColor.call(this);
    }
}

Although your question pertains to JavaScript, it's worth considering using CSS for such tasks:

a.ClassName {
    color: yellow; /* Default Color - optional */
}
a.ClassName:hover {
    color: green; /* Change color on mouseover */
}

I hope this explanation proves helpful!

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

image appears hidden by object displaying a YouTube video due to z-index property

I am attempting to overlay a png image on top of an object element that contains a YouTube video. See the code snippet below: <object> scripts... </object> <img src='src' style='position:absolute;top:-10px;z-index:99;' ...

"Utilizing Date Labels on the X-axis in Google Chart API: A Step-by-Step

Is it possible to create a chart using Google Chart API where the X-axis values represent the days in a month? I have a set of data points that are not evenly distributed. For example: Date - Value 1/1/2009 - 100 1/5/2009 - 150 1/6/2009 - 165 1/13/2009 - ...

Having trouble accessing information from the useSelector hook in Redux

I am able to access the information stored in Redux by using console.log, but I encounter a type error when trying to access specific parts of this information. const profile = useSelector(state => state); console.log(profile); // Successfully prin ...

Unleash the full potential of React and material-ui with the Raised Button feature - find out how to effortlessly keep all

This snippet showcases the code for my custom Buttons component: import React from 'react'; import RaisedButton from 'material-ui/RaisedButton'; const style = { button: { margin: 2, padding: 0, minWidth: 1, }, }; cons ...

Is there a feature in VS Code that can automatically update import paths for JavaScript and TypeScript files when they are renamed or

Are there any extensions available for vscode that can automatically update file paths? For example, if I have the following import statement: import './someDir/somelib' and I rename or move the file somelib, will it update the file path in all ...

Updating array content based on property criteria

I've been tackling a project in Angular where I have two arrays set up like this: array1 = [ { Name: "Jack", Id: "1", Location: "UK" }, { Name: "Rose", Id: "2", Location: ...

Mismatch between collection queries' IDs in MongoDB and Mongoose

I am currently working on an application that allows users to organize potluck events and invite other users to participate. While it may seem like a straightforward task, I have encountered a problem that I can't seem to solve: The issue I am facing ...

Troubleshooting tips for resolving encoding issues during XML to JSON conversion

I am currently working with an XML file and I need to convert it into JSON format using Node.js and then display it in HTML. Below is the content of the XML file: <?xml version="1.0" encoding="windows-1251" ?> <ROWDATA> &l ...

Tabulator - Using AJAX to retrieve a JSON document

I am currently working on importing a json file from an Azure blob container using Azure Data Factory. Despite closely following the documentation and researching various resources on Stack Overflow, I am facing challenges with making the ajax request fun ...

Warning: The use of jQuery load to trigger a Synchronous XMLHttpRequest on the main thread is now considered deprecated

$('#in-view-contents').load("/browse/".concat(selectedId), function(responseData){ var contentsLabelEl = document.getElementById("refined-contents-container"); contentsLabelEl.style.display = "block"; var arrayOfReloadScripts = ["/js/ ...

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 ...

The Jquery widget for autocompletion - "select( event, ui )"

I've implemented jquery for my autocomplete search bar. <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8. ...

if statement not recognizing data returned from PHP function

I'm currently working with a function that is being used for an AJAX query: var formData = $(this).serialize(); //store form names and values in an array called 'formData' $.get('filtertest.php',formData,processData); //jQ ...

How can you compare input text to the input value attribute using jQuery?

Consider this scenario: the page displays the following input element... <input class="textInput error" id="accountMailaddress" name="user[email]" size="30" type="text" value="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail=" ...

Is it possible to use the Shiny conditionalPanel in a horizontal orientation?

Currently, I am working on crafting a shiny app that utilizes sidebarLayout() and the goal is to display either one or two plots side by side in the mainPanel(). The decision on how many plots to show is based on an input value set in the sidebarPanel(). ...

Resolving the issue of data transmission within Yii2's framework: Page-to-page data

I'm currently using Yii2-advanced-app and I have encountered an issue. I want to pass the selected value from a dropdown menu to a PHP code that displays a list with checkboxes on the same page. Here is an image for reference on what I am trying to ac ...

Adding data to a pre-made JavaScript file template to create a fresh document

In my web application, I have a form with multiple inputs: <form action=""> Title1:<br> <input type="text" name="title1"> <input type="text" name="title1Description"> <br> Title2:<br> <input t ...

Clicking on the Submit button of the post form simply refreshes the page

Every time I try to submit values from an HTML form, the page reloads without any changes. I've double-checked the routes and controller, but everything seems correct. Solution <div class="panel-body"> @if (session('status')) ...

Exhibition: Sequential Images Transition Using JQuery

Hey there! I've been experimenting with fading images in and out of this gallery. I tried using the following code: $('#slides').fadeTo(3000, 0.0); If you want to check it out, here's a link to my pen: https://codepen.io/anon/pen/gwRX ...