Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: Hide elements by class name

Tags:

javascript

I have an html element that I want to hide from view, but I can't access that element by an ID because it has no ID and I can't assign an ID to it. It has a class assigned to it though. Is there any possible way to hide this element from view without having it's id?

like image 451
lewisqic Avatar asked Aug 24 '10 20:08

lewisqic


2 Answers

There's getElementsByClassName in some browsers, but it's not as widely supported as getElementById. Note that it yields an array of elements, instead of just a single element, as several elements can have the same class.

If you can assign an ID to a parent you might be able to access it in some other way:

document.getElementById('parent').getElementsByTagName('div')[3] // or whatever
like image 158
David Hedlund Avatar answered Oct 07 '22 01:10

David Hedlund


The following html file contains code to toggle, hide, show div by class and id. By using class it is possible to hide a set(group) of divisions.

<head>

    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
    <script type="text/javascript">
    /*function to toggle visibility of class*/
            function toggle_visibility(classname) { $("."+classname).toggle(); }
    /*function to hide class*/
            function hide_visibility(classname) { $("."+classname).hide(); }
    /*function to show class*/
            function show_visibility(classname) { $("."+classname).show(); }
    /*function to hide individual div by id*/
            function hide_visibility(classname) { $("#"+classname).hide(); }
    /*function to show individual div by id*/       
            function show_visibility(classname) { $("#"+classname).show(); }
    </script>

</head>

<body>

    <button onclick="toggle_visibility('class1');">Toggle visibility of class 1</button><br/>
    <button onclick="hide_visibility('class1');">Hide class 1</button><br/>
    <button onclick="show_visibility('class1');">Show class 1</button><br/>
    <button onclick="show_visibility('heading1');">Show heading 1</button><br/>
    <button onclick="hide_visibility('heading1');">Hide heading 1</button><br/>

    <div class="class1" id="heading1"><h1>Heading 1</h1></div>
    <div class="class1"><h2>Heading 2</h2></div>
    <div class="class1"><h3>Heading 3</h3></div>
    <div class="class1"><h4>Heading 4</h4></div>
    <div class="class1"><h5>Heading 5</h5></div>
    <div class="class1"><h6>Heading 6</h6></div>

</body>
like image 30
Naveen Avatar answered Oct 07 '22 00:10

Naveen