本文實例講述了JavaScript實現獲取dom中class的方法。分享給大家供大家參考。具體實現方法如下:
<!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>
希望本文所述對大家的javascript程序設計有所幫助。