Home >Web Front-end >JS Tutorial >JavaScript implementation of methods to obtain classes in dom_javascript skills

JavaScript implementation of methods to obtain classes in dom_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:15:014100browse

The example in this article describes the JavaScript implementation method of obtaining the class in the dom. Share it with everyone for your reference. The specific implementation method is as follows:

<!DOCTYPE html>
<html>
<head lang="en">
 <meta charset="UTF-8">
 <title></title>
 <script>
  function getClass(node,classname) { 
   if(node.getElementsByClassName) {
    return node.getElementsByClassName(classname);
 //如果存在该标签 就返回
   } else {
    var elems = node.getElementsByTagName(node),
      defualt = [];
    for (var i = 0; i < elems.length; i++) {
 //遍历所有标签
     if(elems[i].className.indexOf(classname) != -1) {
 //查找相应类名的标签
      defualt[defualt.length] = elems[i];
     }
    }
    return defualt;
   }
  }
   window.onload = function () {
   var text = document.getElementById('text'),
    cs = getClass(text,'cs');
     document.write(cs.innerHTML='cs');
  }
 </script>
</head>
<body>
 <div id="text"><div class="cs">textcss</div></div>
</body>
</html>

I hope this article will be helpful to everyone’s JavaScript programming design.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn