What is the best way to apply a Javascript function to multiple tags that share a common id?

I am experimenting with javascript to create a mouseover effect that changes the text color of specific tags in an HTML document. Here is an example:

function adjustColor() {
  var anchorTags = document.querySelectorAll("#a1");
  anchorTags.forEach(function(tag) {
    tag.style.color = "green";
  });
}
<div onmouseover="adjustColor()">
  <a id="a1">Color</a>
  <a id="a1">Names</a>
  <a id="a1">Places</a>
</div>

Currently, only the text color of the "Color" tag changes to green upon mouseover and not Names and Places. Is there a way for my function to apply the color change to all anchor tags with similar IDs?

Answer №1

id must be unique in order to properly target elements. To achieve the same result, document.querySelectorAll can be used along with a class since multiple elements can share the same class.

//retrieve all elements with the same class name
// iterate through them using array#forEach method
document.querySelectorAll('.a1').forEach(function(item) {
  // add an event listener to each element
  item.addEventListener('mouseover', function(e) {
    this.style.color = "green";
  })
})
<div>
  <a class="a1">Color</a>
  <a class="a1">Names</a>
  <a class="a1">Places</a>
</div>

Note: This code will color individual text on mouseover. If the goal is to color all the text at once, then the event handler should be added to the parent element.

Answer №2

It is recommended to utilize classes.

In JavaScript, you can retrieve an array of elements sharing the same class.

function handleBoxMouseover () {
  // Select all child elements with the class "a1" and store them in an array
  var childElements = document.getElementsByClassName('a1');

  // Loop through the new array and change the color based on the index
  for (var i = 0; i < childElements.length; i++) {
    childElements[i].style.color = 'green';
  }
}
<div onmouseover="handleBoxMouseover()">
  <a class="a1">Color</a>
  <a class="a1">Names</a>
  <a class="a1">Places</a>
</div>

Just a heads up:

Instead of modifying inline styles, you could also assign a class to the child elements to alter the color.

Answer №3

Implement the mouseoverbox1() function on each a element instead of the parent div, passing in the parameter this. Inside the function, reset the color property for all a elements and then set the color only for the currently hovered a element.

Note: The use of id should be unique within a document; consider using class instead.

Here is a suggested approach:

function mouseoverbox1(that){
  document.querySelectorAll("#tagContainer > a.a1").forEach(function(el){
    el.style.color = "";
  });
  that.style.color = "green";
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="tagContainer">
    <a class="a1" onmouseover="mouseoverbox1(this)">Color</a>
    <a class="a1" onmouseover="mouseoverbox1(this)">Names</a>
    <a class="a1" onmouseover="mouseoverbox1(this)">Places</a>
</div>

Answer №4

Is there a way for my function to accept changes to all anchor tags with similar IDs?

IDs should be unique to avoid issues like this.

If you want to keep the same ID, avoid using getElementById and instead use querySelectorAll

function highlightAnchorTags() {
    document.querySelectorAll("[id='a1']").forEach( function( element ) {
        element.style.color = "green";
   });
}

Check out the demo below:

function mouseoverbox1(){
    document.querySelectorAll("[id='a1']").forEach( function( ele ){
       ele.style.color = "green";
    });
}
<div onmouseover="mouseoverbox1()">
    <a id="a1">Color</a>
    <a id="a1">Names</a>
    <a id="a1">Places</a>
</div>

Answer №5

Instead of relying on multiple JavaScript solutions, here is a simple and effective CSS solution for the problem:

div a:hover {
  color: green;
}
<div>
  <a id="a1">Color</a>
  <a id="a1">Names</a>
  <a id="a1">Places</a>
</div>

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

Tips for concealing the currently playing track title on a media player

I'm looking for a way to conceal the track title displayed in the media player on Internet Explorer. Here's the code I currently have: <object id="mediaPlayer" width="320" height="240" classid="CLSID:6BF52A52-394A-11d3-B153-00C04F79FAA6" type ...

Dealing with errors effectively in AngularJS $http requests

What is the best approach for handling connection errors in Angular? When using the $http POST service: dossierService.getDossier(uid) .then(function (result) { vm.dossier = result.dossier; }, function (error) { handleErro ...

The server was unable to start because NPM was unable to navigate to the wrong directory and locate the package.json file

I recently used vue create to start a project and everything went smoothly. However, when I tried to run npm run serve, I encountered an issue where node couldn't locate the package.json file that was generated during the project creation process. Th ...

Trigger jQuery Waypoints Only Once

Utilizing , I am seeking to trigger a specific action when the user scrolls down to the section marked with the class div1. However, the action should only occur once and not repeatedly each time the user reaches that point. — just once $('.div1&ap ...

Is it possible for asynchronous functions to write to the same object concurrently and result in invalid values?

I have been experimenting with the code below to see if it can cause any issues with the integer i in the object context. My tests so far have not revealed any problems. // Node.js (v10.19.0) const Promise = require('promise') // object access ...

React.js pagination - removing empty values from an array

I'm currently working on implementing pagination logic that automatically updates the page numbers when the last index is clicked. For example: 1 2 3 4 5 If a user clicks on the number 5, it should display: 2 3 4 5 6 and so forth... I have succe ...

Verify login availability using Javascript auto-check

For quite some time now, I've been grappling with a significant issue that has been consuming my attention. I am determined to implement an auto-check login availability feature in the registration form of my website. My goal is for it to verify the ...

What is the process for determining the area of the section?

Take a look at this page as an example - scrolling down on responsive devices reveals related navigation areas which I aim to change with scrollspy (affix fixed navigation). Having a bootstrap navbar, when on the corresponding section of the navbar while u ...

Is it necessary to only override the monospaced font?

Can the monospace font in Angular Material be customized for just the <code>foo</code> blocks? I want to use a font where the number zero 0 looks distinct from the letter oh O. ...

What is the process for extracting data from latitude and longitude in order to generate a marker on Google Maps using a script

I have an HTML input text and want to pass coordinates to create a marker on Google maps. Check out the code here: jsfiddle.net/#&togetherjs=r3M9Kp7ff7 What is the best way to transfer this data from HTML to JavaScript? <label for="latitude">L ...

Alter the dimensions and material displayed on Vue

In my Vue.js project, I have a topbar with two divs whose size and content need to be adjusted based on whether the user is logged in. If they are not logged in, it should look like this: <div id='search' width="400px"></div><div ...

Converting wiki content to HTML with the help of PHP and JavaScript

Looking to convert wiki syntax to html? Check out the techniques discussed in this resource: Below is the source code of my php page that appears to be functioning correctly. Feel free to test it out yourself: <? if(!defined('DOKU_INC')) d ...

Utilize a standard PHP script for every subdirectory within a domain

I'm currently working on a website and the design I'm using involves changing the URL in the address bar using the history API when the page content changes through JavaScript and AJAX. However, I also want each "page" of the website to be access ...

A guide to creating an HTTPS request using node.js

I am currently in the process of developing a web crawler. Previously, I utilized the following code for HTTP requests: var http=require('http'); var options={ host:'http://www.example.com', path:'/foo/example' }; ...

"Transcribe as HTML" for embedded IFrame components within Chrome's Inspector tool

When using Chrome's web inspector, there is a helpful "Copy as HTML" option when you right-click on a DOM element. However, it seems that this feature does not include the contents of IFrame tags, even though they are displayed in the inspector as chi ...

Guide on creating 2 select inputs with distinct elements?

Imagine you have two select inputs called 'Favorite Fruits' and 'Least Favorite Fruits'. Both of them contain a list of 5 fruits. // The following code is an example to demonstrate the issue <select name='favoriteFruits'& ...

Preventing Event Propagation in Jquery is Quite a Challenge

I'm feeling a bit perplexed. I have a list of names with checkboxes next to them, and this list is generated dynamically after making a request to the backend. The issue is that every time I click on a checkbox, it immediately becomes unchecked. I no ...

Creating a JavaScript function to selectively blur elements while leaving one in focus

My goal is to blur all elements on a webpage except for the p#this tag using vanilla JavaScript. I am determined to learn the intricacies of JavaScript, so I'm not looking for solutions involving jQuery or CSS. I came across a potential solution on t ...

The Jquery animate function is not compatible with the transform property

I am facing an issue with the Jquery animate function. Despite trying various solutions, I have been unable to get it to work. Below is the HTML code that I have used: <!DOCTYPE html> <html lang="en"> <head> <meta cha ...

enabling the editing of two input fields by clicking on a button

Looking to make two input fields editable with a button click. Once edited, the data from these fields will be sent to separate columns in a database using ajax. Struggling to find a solution through online search. Any advice is appreciated! ...