SitePoint Sponsor

User Tag List

Results 1 to 6 of 6
  1. #1
    SitePoint Enthusiast
    Join Date
    Jun 2010
    Posts
    49
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    how to display a div depending on it's class

    Hi, I have a problem, say that I have 2 css classes, 1 is "test failed" and the other is "test ok". And that i have like 20 diffrent div's with their own id, and class either "test failed" or "test ok".
    Code:
    <div class="ok/failed" id="one-twenty"> </div>

    I would like to (depending on what button the user pushes" display the "ok" test cases or hide them and the same thing for the "failed" one's.

    How can this be done in javascript?


    Tried the following but it does'nt work

    Code:
       
    var allHTMLTags = new Array();
    
    function getElementByClass(theClass) {
    
        //Create Array of All HTML Tags
        var allHTMLTags=document.getElementsByTagName(“*”);
    
        //Loop through all tags using a for loop
        for (i=0; i<allHTMLTags.length; i++) {
    
        if (allHTMLTags[i].className==theClass) {
    
        allHTMLTags[i].style.display='none';
    
        }
        }
        }
    Also how can I make the below javascript lines compatible with other browsers besides IE explorer (mainly firefox)?



    Code:
    function HideContent(d) {
    if(d.length < 1) { return; }
    document.getElementById(d).style.display = "none";
    }
    function ShowContent(d) {
    if(d.length < 1) { return; }
    document.getElementById(d).style.display = "block";
    }
    Thanks

  2. #2
    SitePoint Addict MrBaseball34's Avatar
    Join Date
    Sep 2002
    Location
    Round Rock, Texas
    Posts
    277
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Best way to do this is for you to post a url with a non-working demo, otherwise we have to recreate the entire scenario and most people won't do this.

    If you can create a simple page with say 5 each of the failed and ok divs along with the javascript included in the page, that would be very helpful to anyone wanting to help out.

    Also, please describe your naming conventions for the id attributes for these divs, 'one-twenty' doesn't make sense. If you had them with numbers, it might make things easier.
    MrBaseball34
    Hook'Em Horns!

  3. #3
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,684
    Mentioned
    99 Post(s)
    Tagged
    4 Thread(s)
    I've put together some simple test code, that makes use of some well-known pieces of scripting for handling classes.

    One of those is a cross-browser compatible getElementsByClassName and the other is a group of hasClass, addClass and removeClass functions, to which I've added a toggleClass function too.

    Here's the guts of the rest of the code.

    Code html4strict:
     
    <h1>Tests</h1>
    <p>
        <input id="toggleok" type="button" value="Toggle OK">
        <input id="togglefailed" type="button" value="Toggle Failed">
    </p>
    <div id="tests">
    </div>

    20 random tests are created.

    Code javascript:
    function createRandomTests(target, max) {
        var divs, i;
        divs = document.createDocumentFragment();
        for (i = 0; i < max; i += 1) {
            divs.appendChild(createTestDiv(i));
        }
        target.appendChild(divs);
    }
    createRandomTests(document.getElementById('tests'), 20);

    Each test being similar to the following HTML

    Code html4strict:
    <div id="test7" class="test ok">Test 7</div>

    which are created with:

    Code javascript:
    function createTestDiv(i) {
        var div = document.createElement('div');
        if (Math.random() * 100 > 50) {
            addClass(div, 'ok');
        } else {
            addClass(div, 'failed');
        }
        div.id = 'test' + i;
        div.appendChild(document.createTextNode('Test ' + (i + 1)));
        return div;
    }

    and are then toggled with the likes of:

    Code javascript:
     
    function toggleOk() {
        var tests, i;
        tests = document.getElementsByClassName('ok');
        for (i = 0; i < tests.length; i += 1) {
            toggleClass(tests[i], 'hide');
        }
    }
    document.getElementById('toggleok').onclick = toggleOk;

    Here's the full test code:

    Code html4strict:
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
    <html lang="en">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Toggle Tests</title>
    <style type="text/css">
    #tests { border: 1px solid black; border-bottom: none; }
    #tests div { border-bottom: 1px solid black; }
    .ok { background: lightgreen; }
    .failed { background: red; }
    .hide { display: none; }
    </style>
    </head>
    <body>
    <h1>Toggle Tests</h1>
    <p>
        <input id="toggleok" type="button" value="Toggle OK">
        <input id="togglefailed" type="button" value="Toggle Failed">
    </p>
    <div id="tests">
    </div>
    <script type="text/javascript">
    Object.prototype.getElementsByClassName = document.getElementsByClassName = document.getElementsByClassName || function(className) {
    	className = className.replace(/\s+/g, ' ').replace(/^\s|![A-Za-z0-9-_\s]|\s$/g, '').split(' ');
     
    	for (var i = 0, elements = this.getElementsByTagName('*'), elementsLength = elements.length, b = [], classNameLength = className.length, passed = true; i < elementsLength; i++, passed = true) {
    		for (var j = 0; j < classNameLength && passed; j++) {
    			passed = (new RegExp('(^|\\\s)' + className[j] + '(\\\s|$)', 'i')).test(elements[i].className);
    		}
     
    		if (passed) {
    			b.push(elements[i]);
    		}
    	}
     
    	return b;
    };
    </script>
    <script type="text/javascript">
    function hasClass(ele,cls) {
    	return ele.className.match(new RegExp('(\\s|^)'+cls+'(\\s|$)'));
    }
     
    function addClass(ele,cls) {
    	if (!this.hasClass(ele,cls)) ele.className += " "+cls;
    }
     
    function removeClass(ele,cls) {
    	if (hasClass(ele,cls)) {
        	var reg = new RegExp('(\\s|^)'+cls+'(\\s|$)');
    		ele.className=ele.className.replace(reg,' ');
    	}
    }
     
    function toggleClass(ele,cls) {
    	if (hasClass(ele,cls)) {
        	removeClass(ele, cls);
        } else {
            addClass(ele, cls);
    	}
    }
    </script>
     
    <script type="text/javascript">
    function createTestDiv(i) {
        var div = document.createElement('div');
        if (Math.random() * 100 > 50) {
            addClass(div, 'ok');
        } else {
            addClass(div, 'failed');
        }
        div.id = 'test' + i;
        div.appendChild(document.createTextNode('Test ' + (i + 1)));
        return div;
    }
     
    function createRandomTests(target, max) {
        var divs, i;
        divs = document.createDocumentFragment();
        for (i = 0; i < max; i += 1) {
            divs.appendChild(createTestDiv(i));
        }
        target.appendChild(divs);
    }
     
    function toggleOk() {
        var tests, i;
        tests = document.getElementsByClassName('ok');
        for (i = 0; i < tests.length; i += 1) {
            toggleClass(tests[i], 'hide');
        }
    }
     
    function toggleFailed() {
        var tests, i;
        tests = document.getElementsByClassName('failed');
        for (i = 0; i < tests.length; i += 1) {
            toggleClass(tests[i], 'hide');
        }
    }
     
    document.getElementById('toggleok').onclick = toggleOk;
    document.getElementById('togglefailed').onclick = toggleFailed;
    createRandomTests(document.getElementById('tests'), 20);
    </script>
    </body>
    </html>
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  4. #4
    do righteous deeds
    Join Date
    Aug 2006
    Location
    Türkiye Turkey تركيى
    Posts
    266
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Code JavaScript:
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
    <html lang="en">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Toggle Tests</title>
    <style type="text/css">
    .ok { background: lightgreen; }
    .failed { background: red; }
    </style>
     
    <script type="text/javascript">
     
    function showHide(c){
     
    for(var i=1; i<21; i++){
    var el= document.getElementById("test"+i);
    if(el.className==c) {el.style.display= (el.style.display=="none")? "block" : "none"; }
    }
    }
     
    </script>
     
    </head>
    <body>
    <h1>Toggle Tests</h1>
    <p>
     
        <input type="button" value="Toggle OK" onclick="showHide('ok')">
        <input type="button" value="Toggle Failed"  onclick="showHide('failed')">>
    </p>
     
    <div class="failed" id="test1">Test 1</div>
    <div class="failed" id="test2">Test 2</div>
    <div class="ok" id="test3">Test 3</div>
    <div class="failed" id="test4">Test 4</div>
    <div class="failed" id="test5">Test 5</div>
    <div class="failed" id="test6">Test 6</div>
    <div class="ok" id="test7">Test 7</div>
    <div class="failed" id="test8">Test 8</div>
    <div class="failed" id="test9">Test 9</div>
    <div class="ok" id="test10">Test 10</div>
    <div class="failed" id="test11">Test 11</div>
    <div class="failed" id="test12">Test 12</div>
    <div class="failed" id="test13">Test 13</div>
    <div class="ok" id="test14">Test 14</div>
    <div class="failed" id="test15">Test 15</div>
    <div class="failed" id="test16">Test 16</div>
    <div class="ok" id="test17">Test 17</div>
    <div class="failed" id="test18">Test 18</div>
    <div class="failed" id="test19">Test 19</div>
    <div class="ok" id="test20">Test 20 </div>
     
    </body>
    </html>
    Last edited by ScallioXTX; Aug 8, 2010 at 19:26. Reason: Removed unnecessary code comment
    The Time Through Ages
    1. By the Time, 2. Verily Man is in loss, 3. Except such as have Faith, and do righteous deeds, and (join together) in the mutual enjoining of Truth, and of Patience and Constancy.

  5. #5
    do righteous deeds
    Join Date
    Aug 2006
    Location
    Türkiye Turkey تركيى
    Posts
    266
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    if(el.className==c)
    must be
    if(el.className.split(" ")[1]==c)


    <div class="failed"
    must be
    <div class="test failed"

    <div class="ok"
    must be
    <div class="test ok"

    in the above code.

    Code JavaScript:
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
    <html lang="en">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Toggle Tests</title>
    <style type="text/css">
    .ok { background: lightgreen; }
    .failed { background: red; }
    </style>
     
    <script type="text/javascript">
    // The Time Through Ages. In the Name of Allah, Most Gracious, Most Merciful. 1.By the Time, 2.Verily Man is in loss, 3. Except such as have Faith, and do righteous deeds, and (join together) in the mutual enjoining of Truth, and of Patience and Constancy.
     
    function showHide(c){
     
    /*
     var n=document.getElementById('test1');
     alert(n.className);
     
     var t=n.className.split(' ');
     alert(t[1]);
     
    */
     
    for(var i=1; i<21; i++){
    var el= document.getElementById("test"+i);
    if(el.className.split(" ")[1]==c) {el.style.display= (el.style.display=="none")? "block" : "none"; }
    }
    }
     
    </script>
     
    </head>
    <body>
    <h1>Toggle Tests</h1>
    <p>
     
        <input type="button" value="Toggle OK" onclick="showHide('ok')">
        <input type="button" value="Toggle Failed"  onclick="showHide('failed')">>
    </p>
     
    <div class="test failed" id="test1">Test 1</div>
    <div class="test failed" id="test2">Test 2</div>
    <div class="test ok" id="test3">Test 3</div>
    <div class="test failed" id="test4">Test 4</div>
    <div class="test failed" id="test5">Test 5</div>
    <div class="test failed" id="test6">Test 6</div>
    <div class="test ok" id="test7">Test 7</div>
    <div class="test failed" id="test8">Test 8</div>
    <div class="test failed" id="test9">Test 9</div>
    <div class="test ok" id="test10">Test 10</div>
    <div class="test failed" id="test11">Test 11</div>
    <div class="test failed" id="test12">Test 12</div>
    <div class="test failed" id="test13">Test 13</div>
    <div class="test ok" id="test14">Test 14</div>
    <div class="test failed" id="test15">Test 15</div>
    <div class="test failed" id="test16">Test 16</div>
    <div class="test ok" id="test17">Test 17</div>
    <div class="test failed" id="test18">Test 18</div>
    <div class="test failed" id="test19">Test 19</div>
    <div class="test ok" id="test20">Test 20 </div>
     
    </body>
    </html>
    The Time Through Ages
    1. By the Time, 2. Verily Man is in loss, 3. Except such as have Faith, and do righteous deeds, and (join together) in the mutual enjoining of Truth, and of Patience and Constancy.

  6. #6
    om nom nom nom Stomme poes's Avatar
    Join Date
    Aug 2007
    Location
    Netherlands
    Posts
    10,272
    Mentioned
    50 Post(s)
    Tagged
    2 Thread(s)
    Quote Originally Posted by MrBaseball
    Also, please describe your naming conventions for the id attributes for these divs, 'one-twenty' doesn't make sense. If you had them with numbers, it might make things easier.
    Wouldn't make much more sense as class="twenty-one" really. And you can't have class="21".

    snowball: you need to be very careful with your quotes. I don't know if you have them in your actual code, but the code you posted:
    Code:
     var allHTMLTags=document.getElementsByTagName(“*”);
    has bad quotes. You need the ascii quotes that appear when you hit the " key (so, straight quotes, not curved). If you have a language issue with your keyboard, you need to get it sorted out... however it's most likely your text editor. Make sure it's set to either Latin-1 (iso-8895-1) or utf-8, and not some weird ansi default. Slanted quotes WILL cause problems even in good code in some or all browsers.


Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •