DOM 방법

2426 단어
getElementsByClassName




    
    Document
    



    
    window.onload=function () {
        var ul1=document.getElementById('ul1');
        var aLi=getElementsByClassName(ul1,'li','box');
        console.log(aLi);
        function getElementsByClassName(parent,tagName,className) {
            var aEls=parent.getElementsByTagName(tagName);
            var arr=[];
            for (var i = 0; i < aEls.length; i++) {
                var aClassName=aEls[i].className.split(' ');
                for (var j = 0; j < aClassName.length; j++) {
                    if (aClassName[j]==className) {
                        arr.push(aEls[i]);
                        break;
                    }
                }
            
        }
        return arr;
    }
}
    
    
  • 111111
  • 2222222
  • 3333333
  • 444444

addclassname




    
    class
    



    
window.onload=function () { var odiv=document.getElementById('div1'); addclass(odiv,'box3'); function addclass(obj,className) { if (!obj.className) { obj.className=className; } else { var arrClassName=obj.className.split(' '); var _index=arrIndexOf(arrClassName,className); if (_index==-1) { obj.className+=' '+className; } } } function removeclass(obj,className) { if (obj.className) { var arrClassName=obj.className.split(' '); var _index=arrIndexOf(arrClassName,className); if (_index!=-1) { arrClassName.splice(_index, 1) obj.className=arrClassName.join(' '); } } } removeclass(odiv,'box'); function arrIndexOf(arr,v) { for (var i = 0; i < arr.length; i++) { if (arr[i]==v) { return i; } } return -1; } }

좋은 웹페이지 즐겨찾기