1. 程式人生 > >JS選擇器練習實現簡單的封裝

JS選擇器練習實現簡單的封裝

獲取所有的div和p標籤,併為其加上背景顏色

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <style type="text/css">
            div{
                width: 100px;
                height: 30px;
                border: 1px solid #fff
; padding: 5px 5px; }
p{ width: 100px; height: 100px; display: block; margin-top: 50px; }
</style> </head> <body > <div ></div> <div
>
</div> <p></p> <p></p> </body> </html> <script> //函式封裝 var dom = function(tag){ return document.getElementsByTagName(tag); } var divs = dom('div'); var spans = dom('p'); var
each = function(arr,col){ for(var i=0;i<arr.length;i++){ arr[i].style.background= col; } } each(divs,'red'); each(spans,'#000');
</script>