개발

클래스 이름을 사용하여 요소찾기

에드몽단테스 2010. 6. 2. 13:43
html 에서 아이디 또는 태그이름으로 구성 요소를 찾을 수 있다.

getElementById();
getElementsByTagName();

그러면 클래스 이름으로 요소를 찾을 수 있지 않을까?

검색해보니 getElementsByTagName() 함수가 존재한다.
그런데 파이어폭스 3.6에서는 잘 되지만 IE7.0에서는 이 함수가 존재하지 않는다. (혹시 다른 이름으로 존재할지 모르지)
그래서 사용자 정의 함수로 만들어 보자.

function getElementsByClass(searchClass, node, tag) {
 var classElements = new Array();
  if ( node == null ) node = document;
  if ( tag == null ) tag = '*';
  var els = node.getElementsByTagName(tag);
  var elsLen = els.length;
  var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");
  for (i=0, j=0; i<elsLen; i++) {
   if ( pattern.test(els[i].className))
     classElements[j++] = els[i];
  }
  return classElements;
}


반응형