What is the reason that certain functionalities do not work on an element that has two CSS classes assigned to it

I have a unique situation with two input elements and a button:

<input class="close-acc-usr opt-in" type="text" name="closeAccUsr" />
<input class="close-acc-pin opt-in" type="number" name="closeAccPin" />
<button class="opt-btn close-btn">→</button>

When I click the button, I want both input elements to clear. I tried using this code in the JS event handler function:

document.querySelector('.opt-in').value = '';

However, this code doesn't work as expected. Interestingly, when I replace '.opt-in' with '.close-acc-pin' or '.close-acc-usr', it works perfectly fine. Why does it not work with '.opt-in'?

Answer №1

Make sure to use the querySelectorAll method to target all input elements:

const button = document.querySelector('.opt-btn')
button.addEventListener('click', function() {
  const inputs = document.querySelectorAll('.opt-in');
  inputs.forEach(input => input.value = '')
})
<input class="close-acc-usr opt-in" type="text" name="closeAccUsr" />
<input class="close-acc-pin opt-in" type="number" name="closeAccPin" />
<button class="opt-btn close-btn">→</button>

Answer №2

Why use two classes for the input when you can simply change the opt-in class to an id like this:

<input id="opt-in" class="close-acc-usr" type="text" name="closeAccUsr" />

Then in your Javascript code:

document.querySelector('#opt-in').value = '';

Alternatively, you can also do this:

 document.getElementById('opt-in').value = '';

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

Send the typeahead object result from Angular to another function within the controller

In my current setup, I am utilizing the ui-bootstrap typeahead feature to fetch an object from an external API. Upon selecting the object, it triggers a callback function that stores the results in a separate function within my controller. The challenge l ...

Optimizing HTML and Script loading sequences for efficient execution

I have a query regarding the loading order of scripts in web browsers. I am interested in knowing the most efficient way to redirect users to a mobile website on the client side. For example, if I place a mobile detection script within the <head> se ...

How can I implement a scroll functionality to navigate to the next item in a Vuetify v-carousel?

I'm currently working on a front page layout using the v-carousel component and I am looking to achieve automatic scrolling to the next item without the need for arrows or delimiters. How can I make this happen? Below is my current code: <template ...

JSF CommandLink malfunctions on Firefox when reRendering an entire form

I am currently working on a JSF 1.2 application (Sun RI, Facelets, Richfaces) that was previously designed only for IE6 browsers. However, we now need to extend our support to include Firefox as well. On one of the pages, there is a form with a button tha ...

Why is my React Native button's onPress event not functioning correctly?

I am encountering an issue with the onPress event handler. I have tried multiple solutions but none seem to work with the handleClick function. Here are the different approaches I attempted: onPress={this.handleClick} onPress={this.handleClick()} onPress= ...

Encountering issue while starting npm: expressjs server facing problem with MongoDB

Running npm start on Windows went smoothly, but I encountered an error when trying it on macOS. The error message is as follows: > node ./bin/www.js www error: SyntaxError: Unexpected token ? If you require any additional information, please do not he ...

I am experiencing an issue where the close button image on tap is not closing on the first tap on

Why does the page close on the second tap instead of the first tap when using an iPhone? The image changes on tap but doesn't close as expected. $("#privacy-close-btn").mouseenter(function() { $("#privacy-close-btn").css("display", "none"); $(" ...

Unable to precisely reach the very bottom of the scrollbar

When trying to move to the bottom of the scrollbar, I seem to reach a bit higher than the actual bottom. https://i.stack.imgur.com/Vt83t.png Here is my code: ws.onmessage = function (event) { var log = document.getElementById('log') ...

Start fresh with the count for every individual table

In my HTML document, I have multiple tables with columns that have classes "valuation" and "valuation_all". If one cell in the "valuation" column contains the text "FAIL", then the corresponding cell in the "valuation_all" column should display "FAIL"; oth ...

Injecting resolve values from UI router into Angular Jasmine tests

I am facing an issue in my Angular application where UI router resolves a promise into the controller. However, when attempting to test this controller using Karma, I receive an error about an unknown provider. How can I inject a mock object into the test ...

When working with Express router callbacks, the Array.includes() method will always return false, the Array.indexOf() method will always return -1, and

After utilizing fs.readFile() and fs.readFileSync() functions to access the content of 'words_alpha.txt', I discovered that the file can be accessed publicly from this link: https://raw.githubusercontent.com/dwyl/english-words/master/words_alpha. ...

Facing challenges in both client-side and server-side components

import axios from 'axios'; import Image from 'next/image'; export const fetchMetadata = async({params}) => { try { const result = await axios(api url); return { title: title, description: Description, } / } catch (error) { con ...

Why does Vue continuously insert undefined values when adding non-consecutive indexes to an array?

In my application, users can select values from a dropdown list and add them to an array by clicking the "add" button. The goal is to use the selected value's id as the index in the array. For example: List of Values 1 - Apple 3 - Bananas 8 - P ...

The issue with element.style.backgroundColor not functioning properly within WordPress

Struggling to make the background of a button change upon hover? I've got the code, but it seems to be working everywhere except in WordPress. Check out the code that should be working here: https://jsfiddle.net/TopoX84/3oqgmjb0/ Want to see it not ...

Steps to access arrays that are embedded in a file and are loaded asynchronously

https://gyazo.com/e80eea9f69c0cbb52cc7929d0a46ea2f The name of the object is totalCount. How can I retrieve the count from it? Object.result was my first attempt, but it returned undefined. For my second attempt: var count = totalCount.resu ...

Error: Missing Required Parameter for PUT Request

I'm encountering an error while trying to execute a PUT request. { "error" : { "status" : 400, "message" : "Required parameter position_ms missing" } } I have consistently used the same format for all previous PUT requests, and everythi ...

Executing two Ajax calls sequentially without using asynchronous functionality

Creating a dynamic menu using two REST APIs to establish a parent/child relationship. The ID of the parent from the first API response is passed to the child API to fetch child records. Encountering issues where setting async false for the child API call ...

Angular 2: The *ngFor directive is unable to locate a suitable differing framework

Below is the code for client.service.ts clients: Client[]; getClientList() { let headers = new Headers(); headers.append('Content-Type', 'application/json'); let authToken = localStorage.getItem('auth_token&apo ...

Is there a way to modify a document without altering its original location?

I attempted to load an entire page using ajax, with the doctype and html tags removed. However, when I tried setting it with the following code: document.documentElement.innerHTML=xmlhttp.responseText; Google Chrome returned an error message: An invalid ...

The CSS top border is failing to display

For a school project, I've been attempting to add a top border to a set of hyperlinks in order to separate them from the title. However, after spending over an hour on this task, I still can't seem to get it to work. Below is the CSS code for th ...