Choose all elements with a specific class name without the need to specify their position in the list

I'm working on adding a function to my WordPress site that will allow me to show/hide page elements with a specific class. For example, I want any elements (such as rows, containers, and text blocks) that have the 'show-hide' class to be hidden or shown when a button is clicked.

While I have successfully implemented this function, I believe there might be a more efficient way to achieve the same outcome. I would like to find a method that allows me to select all instances of the show-hide class on the page without having to specify individual numbers ([1], [2], [3], etc.) each time.

Since I am new to javascript, I would appreciate any guidance or advice on how to generate a range of values or use wildcard symbols (*) to simplify this process.

function myFunction() {
  var x = document.getElementsByClassName("show-hide");

  for (var i = 0; i < x.length; i++) {
    if (x[i].style.display === "none") {
      x[i].style.display = "block";
    } else {
      x[i].style.display = "none";
    }
  }
}

Answer №1

To achieve this functionality, a loop can be utilized. Here is a more concise way to accomplish the task:

for(let element of Array.from(document.getElementsByClassName("show-hide"))) {
   element.style.display = (element.style.display === 'block') ? 'none' : 'block';
}

Answer №2

To convert your HTML Collection into an array and utilize the map method, you can follow this approach:

function toggleVisibility() {

  Array.from(document.querySelectorAll(".show-hide")).map(function(element){
    if (element.style.display === "none") { 
      element.style.display = "block" 
    } else {
      element.style.display = "none";
    }
  })

};

Answer №3

It has been suggested in the comments that you are seeking a solution involving looping:

function toggleVisibility() {
  var elements = document.getElementsByClassName("show-hide");

  [...elements].forEach(element => {
    if (element.style.display === "none") {
      element.style.display = "block";
    } else {
      element.style.display = "none";
    }
  });
}

Take note of the [...elements] spread operator, which can convert an iterable object (such as an HTMLCollection) into an array.

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

Press the body to update state in React and close the dropdown

Seeking a solution for closing a dropdown menu when a user clicks outside of it or on another element? Consider the following code snippet written in React: var Hello = React.createClass({ getInitialState() { return { openDropdown: false ...

Is there a way to delegate properties in Angular 2+ similar to React?

When working with React, I have found it convenient to pass props down dynamically using the spread operator: function SomeComponent(props) { const {takeOutProp, ...restOfProps} = props; return <div {...restOfProps}/>; } Now, I am curious how I ...

JavaScript functioning properly in Google Chrome and Firefox but not in Internet Explorer 9

Welcome to the Lottery random generator tool! Feel free to use this in Google Chrome or Firefox, but please note that it may not work properly in Internet Explorer 9. If you encounter any issues while using this tool on IE9 and receive an error message st ...

Obtaining the latest state within the existing handler

In my React application, I have a handler that shuffles the state entry data: state = { data:[1,2,3,4,5] }; public handleShuffle = () => { const current = this.state.data; const shuffled = current .map((a: any) => [Math.random() ...

Removing text that was added via the chart renderer in Highcharts can be accomplished by identifying the specific element

Instead of using a legend in my graph, I have added labels directly to the series (view example here). After drawing the graph with these labels attached, the user can click a button to add another series which hides some existing lines successfully. Howev ...

Getting the Correct Nested Type in TypeScript Conditional Types for Iterables

In my quest to create a type called GoodNestedIterableType, I aim to transform something from Iterable<Iterable<A>> to just A. To illustrate, let's consider the following code snippet: const arr = [ [1, 2, 3], [4, 5, 6], ] type GoodN ...

Javascript regular expressions are not functioning as expected

When testing the string "page-42440233_45778105" against the pattern "(page-\d+_\d+)", an online tester at was able to successfully find a match. However, when executing the code in browser js, the result is null. Why might this be? var re = ne ...

Learn the process of sending both Header and Body data in a POST request using Axios with Vue.js

I'm currently attempting to call the post API of AWS Cognito's Token endpoint. The API functions perfectly when tested in my Postman client, but I am encountering issues when implementing it in my VueJS code. Here is a snippet of my code: test. ...

CoffeeScript:: I can't understand why the function body returns when using ajax

Hey there, I'm new to Coffeescript and have a question regarding Ajax. jQuery -> api = getId: -> res = [] $.ajax dataType: "jsonp" url: "http://localhost:3004/videos.json" success: (data) => ...

What is the most effective way to integrate webkitSpeechRecognition into a Vue.js project?

I found a demo at this link, but I'm having trouble understanding it. Can you provide a simple implementation? <div id="app"> <v-app id="inspire"> <v-container fluid> <v-layout row wrap justify-cen ...

React to the Vue: Only activate the event if the key is pressed twice consecutively

In my application, I am creating a unique feature where users can trigger a window to appear by inputting the symbol @ (shift + 50). This will allow them to access predefined variables... <textarea @keyup.shift.50="showWindow"></textarea> My ...

Triggering a click event on various instances of a similar element type using the onclick function

Hey there, I'm a newcomer to Javascript. I've been practicing my Javascript skills and trying to replicate something similar to what was achieved in this example: Change Button color onClick My goal is to have this functionality work for multip ...

What is the best way to import a TypeScript file in index.js?

I've recently developed an application using the react-express-starter template. I have a "server" directory where the backend is created by nodejs, containing an index.js file: const express = require('express'); const app = express(); c ...

How can the onclick attribute be modified in an HTML document?

I am looking to update the data-pro-bar-percent attribute of a progress bar from 80 to 100 when a specific link is clicked. The change in attribute needs to be as follows: data-pro-bar-percent="80" --> data-pro-bar-percent="100" This is the current HTML ...

The absence of jasmine-node assertions in promises goes unnoticed

Everything seems to be running smoothly with the code below, except for the assertion part. Whenever I run the test using Jasmine, it reports 0 assertions. Is there a way to include my assertions within promises so they are recognized? it("should open sav ...

What could be causing the issue with ng-show in Angular?

When a user clicks on an icon, I want to display a drop-down menu. I attempted to use the ng-show directive for this purpose, but unfortunately, the drop-down menu is not appearing. I created an icon ..., and when clicked, I attempted to open the drop-do ...

appearing like a straightforward process of creating strings in JavaScript

Originally, I thought this task would be easy, but it ended up taking me the entire morning! var insert = '<div class="main_content_half_panel_circle" id="circle_' + c + '"></div><script type="text/javascript">$("#circle_& ...

conceal menu upon click (gradually disappear)

This is a basic HTML/CSS menu. Currently, it is functioning properly for page redirection (href). However, I would like it to hide after being clicked on. I plan to call a function that will initiate an AJAX request upon clicking. Here is the code on JS ...

preventing the page from scrolling whenever I update my Angular view

Whenever I update a part of my model that is connected to my view, my page automatically scrolls. I suspect that the page scrolling is triggered by the view updates. How can I stop this from happening? For instance, here is an example involving a dropdown ...

Troubleshooting AngularJS: Directive unable to access controller's variable within scope

I am facing a challenge with an element that has both a controller and a directive featuring an isolate scope: scope: { dirVar: '= ' } My objective is to execute specific parts of the directive only when a certain variable is true. I am try ...