What happens in the loop when the attribute value matches the ID value?

<style>

    .heading {
        color: red;
    }
    
    .button {
        font-size: 18px;
    }
    
    .skyblue {
        background-color: skyblue;
    }
</style>
Whenever the "data-mh" attribute of an <h1> tag matches the id attribute of a <button> tag, clicking on that button will change its background color. The matching attribute will then be printed on a P tag. While this functionality works with the first button, it does not work with subsequent buttons. /* how can do it by loop */
<h1 class="heading" data-mh="item1">Hello World</h1>
<button class="button" id="item1">Click Here</button>

<h1 class="heading" data-mh="item2">Hello World</h1>
<button class="button" id="item2">Click Here</button>

<h1 class="heading" data-mh="item3">Hello World</h1>
<button class="button" id="item3">Click Here</button>

<p id="demo"></p>
<!-- This Paragraph tag will print my attribute -->

<!-- HTML End -->

<script>
    var x = document.querySelector(".heading").getAttribute("data-mh"); // This variable is to get Attribute of "data-mh"
    var y = document.querySelector(".button"); // Button selection. By clicking this button I will get print my Attribute
    var z = y.getAttribute("id"); // Getting button id to compaire with "data-mh" attribute
    y.onclick = function() {
        //If X (ID) and Z (Attribute) matching then working this Condition
        if (x == z) {
            y.classList.toggle("skyblue");
            document.getElementById("demo").innerHTML = x+" "+z; // This line of code will print my Attribute on P tag
        }
    }
</script>

Answer №1

This piece of code efficiently handles the task by iterating through each button and setting up event listeners as well as comparisons.

// select all buttons on the page
const buttons = document.querySelectorAll(".button");

// iterate over each button
for(const button of buttons)
{
  // add a click listener to the button
    button.addEventListener("click", (event) => {
    // retrieve the button's ID
    const x = button.getAttribute("id");
    /// retrieve the data-mh attribute from the previous element (the heading)
    const z = button.previousElementSibling.getAttribute("data-mh");
    // perform a comparison
    if(x == z)
    {
      button.classList.toggle("skyblue");
      document.getElementById("demo").innerHTML = x+" "+z;
    }
  });
}

Check out this demo: https://jsfiddle.net/w3d0z8Ly/

Answer №2

My response:

var x = document.querySelectorAll(".heading"); // Grabbing the elements with the class "heading"
    var y = document.querySelectorAll(".button"); // Selecting buttons to trigger actions
    function btnClick(e) {
      for(var i = 0; i < x.length; i++) {
        if(e.getAttribute("id") == x[i].getAttribute("data-mh"))  {
          document.getElementById("demo").innerHTML = x[i].getAttribute("data-mh");
        }
      }
      for(var j = 0; j < y.length; j++) {
        y[j].classList.remove("skyblue");  
      }
      e.classList.add("skyblue");
    }
      
.heading {
        color: red;
    }
    
    .button {
        font-size: 18px;
    }
    
    .skyblue {
        background-color: skyblue;
    }
<h1 class="heading" data-mh="item1">Hello World</h1><button class="button" id="item1" onClick="btnClick(this)">Click Here</button>

<h1 class="heading" data-mh="item2">Hello World</h1>
<button class="button" id="item2" onClick="btnClick(this)">Click Here</button>

<h1 class="heading" data-mh="item3">Hello World</h1>
<button class="button" id="item3" onClick="btnClick(this)">Click Here</button>

<p id="demo"></p>

Please verify this information

Answer №3

let elements = document.querySelectorAll(".element");
let containers = document.querySelectorAll(".container");

for (const element of elements) {
  for (const container of containers) {
    element.addEventListener("click", (event) => {
      const id = element.getAttribute("id");
      const dataId = container.getAttribute("data-id");
      if (id == dataId) {
        element.classList.toggle("active");
        document.getElementById("output").innerHTML = id + " is clicked!";
      }
    });
  }
}

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

Manipulate the SQL Table output in PHP before displaying it

I am facing a beginner's problem. I have the following code to access a SQL Table, and before printing it out (which works), I want to check if the "Zustand" in the table is 0 or 1. The function should then change the printout to show "good" for 1 and ...

Assigning IDs to jQuery tabs

My view contains something similar to this: <li><a href="SearchQC.do?mode=view">Add to QC List</a></li> While running, jQuery automatically generates a div with the id ui-tabs-1. How can I modify this ID? UPDATE If the ID remain ...

The JWT authentication appears to be functioning properly when tested on "postman," however, it is encountering issues on the website

When I attempt to verify a user's authentication using tools such as "Postman" or "Insomnia," everything functions correctly (when I set the bearer). However, when I try to log in through the website, I encounter an error here: function authenticateT ...

Issue with default parameter setting in AngularJS $http header

I am encountering a similar problem mentioned in this post: Angularjs set a authorization header The issue I am facing is the need to include an authorization token in my request headers. I have attempted various methods to achieve this- such as setting $ ...

What method is the most effective for preloading images and stylesheets?

One of the main concerns I have is optimizing the load time of my website. I would like to preload images, style sheets, and scripts to ensure a faster loading speed and to prevent users from seeing images loading right before them. Can someone suggest the ...

Guide to attaching a mouse click event listener to a child element within a Polymer custom component

I'm currently facing an issue where I am attempting to attach a click listener to one of the buttons within a custom element during the "created" life cycle callback (even attempted using the "ready" callback with the same outcome). Unfortunately, I ...

Bypass ajax request with the use of a returned promise

I've come across a scenario where I have a function within a class that is designed to return a promise for deleting an item. Here's what the function looks like: function Delete(){ // if(this.id == ""){ // return ?; // } ...

Calculate the duration in years based on milliseconds

I have a validator that verifies whether an individual is at least 18 years old. Here is the validation process: var res = /^([1-2]\d{3})\-(0[1-9]|1[012])\-(0[1-9]|[12][0-9]|3[01])\-([0-9]{4})$/.exec(str); var todays_date = new Date() ...

Make sure to always retrieve the previous state in your React application

After researching and experimenting based on my previous inquiry, I have devised a solution to properly store the state: if (value === 'checkpoint') { if (checked1) { this.setState({checked1 : false}) localStorage.setObject('che ...

What design pattern serves as the foundation for Angularjs? Is mastering just one design pattern sufficient?

Although I have been teaching myself Angular and can understand how to code in it, I realize that simply learning the concepts of AngularJS and coding or tweaking things to solve problems is not enough. Moving forward, my goal is to write effective and sta ...

Adding elements in increasing order based on the array values

I am implementing selectize.js, where the data is added through an array. My goal is to display the dropdown list in the order of DISPLAYORDER defined within the object. The code below generates the lists: option: function(item, escape) { var popular ...

The Function(JS) is specifically designed to only function within the topmost div or quote

Currently, I am facing an issue with a function I have implemented. This function adds a blur effect to words in a Blockquote when the page is loaded. However, I need this function to work for all Blockquotes and different divs on the page, not just the to ...

Tips on resolving issues with form input that is not accepting input on a Mobile device

As a newbie in HTML and CSS, I attempted to design a form with various fields. While the fields work perfectly on larger screens, they do not allow input on smaller screens (mobile devices). I used the Firefox inspect tool to troubleshoot the issue, but c ...

Retrieve the count of ng-if directives that match a specific ng-repeat content

Imagine a scenario where HTML code looks like this: <md-grid-tile class="gray" ng-repeat="carto in cartoList" ng-if="search(carto)"> <md-button ng-click="changeSVG(carto.fileName)" aria-label="carto.displayName"> <img ...

React Nested Grid with Material-UI

https://i.stack.imgur.com/toxDA.jpg I am striving to replicate the layout demonstrated in the image below So far, I have the following code snippet: <Grid container justify=“space-between”> <Grid container item> <Grid ite ...

Tips for transferring contact information from a webpage to an Android or iPhone using an HTML button and integrating JavaScript or PHP

My current project involves adding a feature to a website that allows users to save contact details from the site to their phone (Android or iPhone) with the click of an HTML button. Here's what I have done so far <!DOCTYPE html> <html lang= ...

Trouble with Cufon loading and failing to display properly

Testing scenario: <!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <script type="text/javascript" src="/cufon.js"></script> <script type="text/javascript" src="/font.font.js"></script> </head> &l ...

"Filtering a JSON File Based on Button Data Attributes: A Step-by-

I am working with a set of buttons that have specific data-map attributes as shown below: <button class="btn btn-default mapper" data-map="2015-11-13">Monday</button> <button class="btn btn-default mapper" data-map="2015-11-14">Tuesday&l ...

What is the alternative method for passing a function from one component to another without using an Arrow Function?

In the code snippet below, I encountered an issue while attempting to pass the 'handleChange' method to another component called 'TodoList'. Despite trying to bind the method, the problem persisted. import React from "react"; ...

In JSP, white spaces are automatically removed

I need to display a string that is retrieved from a model object in my JSP view. The string looks like this: String str= " | | "; However, when I attempt to display this string using the model object in the JSP view, the white spaces are missing ...