正则表达式笔记4-封装class

<!doctype html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>封装class</title>
	<script>
		window.onload = function(){

			var oUl = document.getElementById('ul1');

			var aBox = getByClass(oUl, 'box1');

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

				aBox[i].style.color = 'red';
			}

			// JS获取class的方法一(普通版):封装class函数(缺点: 不能识别多个class)
			/*function getByClass(oParent, sClass){

				var arr = [];

				var aEle = oParent.getElementsByTagName('*');

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

					if(aEle[i].className == sClass){

						arr.push(aEle[i]);
					}
				}
				return arr;
			}*/

			// JS获取class的方法二(完美版):
			function getByClass(oParent, sClass){

				var arr = [];

				var aEle = oParent.getElementsByTagName('*');

				var re = new RegExp('\\b'+ sClass + '\\b');

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

					if(re.test(aEle[i].className)){

						arr.push(aEle[i]);
					}
				}
				return arr;
			}
		};
	</script>
</head>
<body>
	<ul id="ul1">
		<li class="box1">111</li>
	    <li>111</li>
	    <li class="box1box2">111</li>
	    <li class="box1 box2">111</li>
	    <li>111</li>
	    <li class="box1">111</li>
	</ul>
</body>
</html>
  

  

posted @ 2017-05-26 11:59  波克比520  阅读(248)  评论(0编辑  收藏  举报