How can a CSS class be used to toggle the visibility of a DIV element with JavaScript?

I've been researching and came across several scripts that allow for toggling the contents of a DIV by clicking on a button, however, they all use IDs.

What I am looking to achieve is similar but using classes instead of IDs. This way, if I want to have multiple DIVs that toggle between hide and show, I won't need to add extra code.

Below is a sample code snippet:

<script language="javascript"> 
function toggle() {
    var ele = document.getElementsByClassName("toggleText")[0];
    var text = document.getElementById("displayText");
    if(ele.style.display == "block") {
            ele.style.display = "none";
        text.innerHTML = "show";
    }
    else {
        ele.style.display = "block";
        text.innerHTML = "hide";
    }
} 
</script>

<a id="displayText" href="javascript:toggle();">show</a> <== click here
<div class="toggleText" style="display: none"><h1>peek-a-boo</h1></div>

Would appreciate any assistance with this matter.

Thank you

Answer №1

Can jQuery be used for this task? Hopefully, as it provides the functionality you need:

http://api.jquery.com/toggle/

$(".class").toggle();
or
$(".class").show();  $(".class").hide();

Answer №2

Figuring out the solution in jQuery shouldn't be too difficult, but since your code is in vanilla JavaScript, here's how you can implement it using JavaScript.

One potential drawback to keep in mind is that some browsers may not support the getElementsByTagName method. I have tested it on IE7 and confirmed that it works, but its compatibility with older versions is uncertain.

var divs = document.getElementsByTagName('div');

var toggle = function() {    
    for (var i = 0, l = divs.length; i < l; i++) {
        if (divs[i].getAttribute('class') == 'problem') 
            if (divs[i].style.display == 'none') divs[i].style.display = '';
            else divs[i].style.display = 'none';
    }
}

document.getElementById('Toggle').onclick = toggle;

Give it a try: http://jsfiddle.net/robert/PkHYf/

Answer №3

Many have mentioned that accomplishing this task in jQuery is simple with a jquery selector and the .hide method. However, if you prefer to learn how to do it without relying on a framework, here are some alternative methods:

Consider these options:

  1. JQuery Method: Utilize jQuery selectors along with the .hide() method.

    $(".CLASSNAME").hide()

  2. Vanilla JS: Dynamic CSS. One solution involves dynamically adding stylesheets to the document head - you can Alter CSS class attributes with javascript?

  3. Vanilla JS: Directly Modify CSS:

        var ss = document.styleSheets;
        for (var i=0; i<ss.length; i++) {
            var rules = ss[i].cssRules || ss[i].rules;
    
            for (var j=0; j<rules.length; j++) {
                if (rules[j].selectorText === ".classname") {
                    rules[j].style.visibility = "none";
                }
            }
        }
    

Answer №4

Could this possibly be achieved by:

document.querySelectorAll('.classname').forEach(element => {
  element.style.display = 'none';
});

Alternatively, gather all the elements intended for hiding inside a parent div and conceal that whole container.

Answer №5

Implementing jQuery:

$(".element").hide();

Replace element with the actual class name.

Answer №6

To hide an element with a specific class, you can use the code $(".className").hide();

The jQuery function $(".somthing") serves the same purpose as $("#somthing"), but it targets classes instead of IDs.

Answer №7

To locate an element by its ID using jQuery Selectors, the syntax is:

$("#id")

To target elements by their classes, simply use this format:

$(".className")

If you prefer not to use jQuery, it can be a bit more challenging, but you can refer to this Stack Overflow post for guidance:

How to getElementByClass instead of GetElementById with Javascript?

Answer №8

If you're looking for a solution using Vanilla JS, check out this helpful resource:

The key is to add or remove the .hidden CSS class.

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 avoiding multiple function calls in React JS when a value changes

How can I avoid multiple function calls on user actions in my demo application? I have tabs and an input field, and I want a function to be called when the user changes tabs or types something in the input field. Additionally, I need the input field value ...

Updating Mongoose References

When updating the Kwizz model with the password from req.body and team ID from req.session, it currently replaces the existing teams array. However, I am looking to simply add 1 to the array instead. I have searched for a solution but couldn't find a ...

Retrieving a result from the reduce function in Angular

Is there a way to use the reduce function in order to return a list of objects? I am currently only able to return a single object with keys as project names and values as hours: { Name1: 9, Name2: 10, Name3: 30, } What changes can I make to my code to ac ...

refetchQueries may be effective for specific queries

Using a Friend component within my AllFriends screen triggers the following mutation: const [deleteUserRelation] = useDeleteUserRelationMutation({ onCompleted: () => { Alert.alert('Unfriended'); }, refetchQueries: [{ query: ...

Comparison: Chrome extension - utilizing default pop-up vs injecting a div directly into the page

I find myself perplexed by the common practices used in popular Chrome extensions. I am currently working on creating my own Chrome extension and after completing a basic tutorial, I have set up a default popup page that appears when clicking the extensi ...

Steps for incorporating Bootstrap 5 pagination without using jQuery

Currently, I am working on incorporating pagination for cards using Bootstrap 5. My reference point is the following link: https://getbootstrap.com/docs/5.0/components/pagination/ While I can find the UI elements, I am struggling to come across a concrete ...

Django Ajax filter displaying issue on HTML page

I'm uncertain about the correctness of my Ajax implementation. When using Django's built-in tags, the objects I pass through Ajax are not appearing on my template HTML page. view_results.html <div> <input id="search" name="search" t ...

Navigating through cors in next.js

Currently, I have set up my front end using Netlify and my backend using Heroku with Next.js For the fetch request on the front end, here is an example: fetch(`https://backendname.herokuapp.com/data`, { method: 'POST', headers: { & ...

Using Angular function to retrieve Firebase snapshot

Trying to access a user's profile image stored in Firebase at /user/[uid]/info/photoURL This is being done using Angular functions. Here is the code snippet: HTML: <img ng-src="{{getImg(user.uid)}}" alt=""> Javascript: $scope.getImg = func ...

Clicking on a link in HTML with the onclick event

I am looking to create a button that will direct me to a different page. Here is the code snippet I have: <div align="right" ><input type="submit" id="logout" onclick="location.href='/login?dis=yes'" value="Sign Out" ></div>& ...

Examples of how to specify a child class in CSS

Presented here is the following structure: <article class="media media--small 48"> <a href="#"> <img src="" class="media__img" alt=""> <i class="s s--plus"></i></a> <div class="media__body"> < ...

Using a jQuery function with onclick events in a loop

I'm faced with a challenge in jQuery/js programming and could use some guidance as I am relatively new to this. function initiateViewingProcess(){ var elen =$MP.data.REG_AS_RS.ASSIGNEE.length; for (i = 0 ; i < elen ; i++) {var dEv ...

Implementing Asynchronous Rendering in React Router 4

I've been working with React Router 4 and trying to implement Redirect(Auth) following a guide. However, I'm facing an issue with rendering based on the promise returned by an AJAX call. It seems like my rendering logic inside the promise is not ...

The picture is malfunctioning

I am experiencing an issue with the placement of an image in my HTML code. When I place the image inside the nav element, it works perfectly fine. However, when I try to put it inside the body or header elements, it doesn't display properly. I am new ...

Is it possible to arrange two items in one column and the rest as columns in MaterialUI Grid?

I need help arranging my arrows in a MaterialUI grid where one points up and the other points down. How can I achieve this layout? Attached below is an image of my current setup and the desired outcome. Here is my code: <Paper className={classes.paper ...

Retrieving a file URL from Sanity within a blocks array

I've been working on a website with Next JS and using Sanity as the CMS. While Sanity has schemas for images, I ran into an issue when trying to handle videos. The documentation recommends using GROQ queries to convert file URLs at the request level, ...

Creating an interactive button using RichFaces and Bootstrap for seamless Ajax functionality

I have a challenge with making a fully clickable span or button that includes a Bootstrap refresh glyph-icon. The current code I have inherited only allows the icon itself to be clicked, leaving the area between the icon and button border unclickable. This ...

Unable to view form data in .php file

How can I change the style of my "Submit" button when a user clicks on it to submit the form? The action attribute calls a PHP file, but the data doesn't show up until I remove the onSubmit attribute from the form. However, without it, I cannot use t ...

bash: The command "nodemon" could not be located

My experience with nodemon has been smooth for the past few months. However, today I encountered an error that I couldn't resolve. Despite uninstalling and reinstalling nodemon, as well as force installing it, I still received the same error message w ...

How to align a div in the center while another div is floated to the right?

Shown below is an example: <div id="mainContainer"> <div id="itemIWantToCenter"></div> <div id="itemIwantFloatedRight"></div> </div> The mainContainerwidth width is set to 100%. The itemIwantFloatedRight widt ...