Jquery Vs JavaScript - Get elements by class name

getElementsByClassName JavaScript and Jquery example

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Jquery Vs Javascript...codesstore.blogspot.com</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.min.js"></script>
<script type="text/javascript">

//-------------Jquery hide divs---------------------
    $(document).ready(function(){
        $("#jquery-hide").click(function(){
            $(".hideme").hide();
        });
    });
    
//-------------JavaScript hide divs------------------

function hideAll(){
    
    var divs=document.getElementsByClassName("hideme");
    for(var i=0;i<divs.length;i++){
        divs[i].style.display="none";
        
    }
    
}

//fixes for IE
onload=function(){
    if (document.getElementsByClassName == undefined) {
        document.getElementsByClassName = function(className)
        {
            var hasClassName = new RegExp("(?:^|\\s)" + className + "(?:$|\\s)");
            var allElements = document.getElementsByTagName("*");
            var results = [];
            var element;
            for (var i = 0; (element = allElements[i]) != null; i++) {
                var elementClass = element.className;
                if (elementClass && elementClass.indexOf(className) != -1 && hasClassName.test(elementClass))
                    results.push(element);
            }
            return results;
        }
    }
}
    
    
</script>
</head>
<body>

    <div class="hideme">
        Content 1
    </div>
    
    <div class="hideme">
        Content 2
    </div>
    
    <a href="#" id="jquery-hide">Jquery Hide</a>
    <a href="javascript:hideAll()" id="js-hide">Javascript Hide</a>
    
</body>
</html>

When using javascript getElementsByClassName not working on IE.I found fixes for IE from a forum...

No comments:

Post a Comment