Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I change the display of a class using JavaScript?

So I have this code:

    function show_all()
    {
    	document.getElementByClassName('login').style.display = 'inline';
    	document.getElementById('button-hide').style.display = 'inline';
    	document.getElementById('button-show').style.display = 'none';
    };
    function hide_all()
    {
    	document.getElementByClassName('login').style.display = 'none';
    	document.getElementById('button-hide').style.display = 'none';
    	document.getElementById('button-show').style.display = 'inline';
    };
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<nav>
    	<input type="button" value="Show login Buttons" id="button-show" onclick="show_all();"/>
    	<input type="button" value="Hide login Buttons" id="button-hide" onclick="hide_all();"/>
    </nav>
        <p class="login">Username:</p>
        <img src="un.png" class="login"/>
        <p class="login">Password:</p>
    <p>Something not ment to be hidden.</p>
        <img src="pass.png" class="login"/>

And I need the entire class to be shown/hidden; I have about 50 blocks with elements with the class "login" and I would like to use only JavaScript to display it.

like image 896
Lèla Null Avatar asked Dec 24 '16 09:12

Lèla Null


1 Answers

I came across the same problem and after having almost no experience with JavaScript, made up this solution in a day. So if there is something wrong with it, please note and comment. I found out the getElementsByClassName() method, which returns an array-like object of all child elements that have all of the given class names, more on getElementsByClassName(). Also, I wanted to be able to do it from one button, so it might depend if you want two buttons to hide or show. You could do it with classList.add() and classList.remove().

Create a CSS class:

.hidden { display: none; }

Then with this function target your HTML elements by class:

function toggleMe() {
    var x = document.getElementsByClassName("comment");
    var i;
    for (i = 0; i < x.length; i++) {
        x[i].classList.toggle("hidden");
    }
}

The for-loop is used to get all the elements with this class and using classList.toggle to toggle the .hidden class for them.

You could also use querySelectorAll() which returns all elements in the document that match specified CSS selectors.

like image 166
Krasimir Milushev Avatar answered Oct 20 '22 17:10

Krasimir Milushev