JS获取(id、class、tag、style、attr)兼容所有

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html> 

 <body>

  <a id='qwe' class='asd' href='http://222sdfad.com'></a>

 

  <script> 

function getClass(tagName, classStr) {     //EG: alert(getClass('*','asd')[0]); alert(getClass('a','asd')[0]); 

if (document.getElementsByClassName) {

return document.getElementsByClassName(classStr)

} else {

var nodes = document.getElementsByTagName(tagName),

ret = []

for (var i = 0; i < nodes.length; i++) {

if (hasClass(nodes[i], classStr)) {

ret.push(nodes[i])

}

}

return ret;

}

function hasClass(tagStr, classStr) {

var arr = tagStr.className.split(/\s+/); 

for (var i = 0; i < arr.length; i++) {

if (arr[i] == classStr) {

return true;

}

}

return false;

}

}

***************************

function getId(id) { //EG: alert(getId('qwe'));

return document.getElementById(id);

}

***************************

function getTag(tag, obj) {   //EG: alert(getTag('a','mrt')[0]);

return ( obj == '' ? document: getId(obj)).getElementsByTagName(tag);

***************************

  function getStyle(obj, attr) {   //EG: alert(getStyle(getId('qwe'),'margin-left'));

if (obj.currentStyle) {

return obj.currentStyle[attr];

} else {

return getComputedStyle(obj, false)[attr];

}

}

/*

author:MRT

获取属性值 

两种方法   $("a").attr("href");   DOM.getAttribute('href')

*/ 

  </script>

 </body>

</html>

posted @ 2015-04-23 11:36  mrt_yy  阅读(1562)  评论(0编辑  收藏  举报