编程语言
首页 > 编程语言> > JavaScript 对 DOM 元素排序

JavaScript 对 DOM 元素排序

作者:互联网

<!DOCTYPE html>
<html>
    <head>
        <style type="text/css">
            #wrap div {
                float: left;
            }
            #wrap:after {
                content: "";
                display: block;
                clear: both;
            }
        </style>
        <script type='text/javascript'>
            document.addEventListener('DOMContentLoaded', function () {
                var wrap = document.querySelector('#wrap');
                var div = document.querySelectorAll('#wrap div');
                var divArr = Array.prototype.slice.call(div).sort(function (a, b) {
                    return a.textContent > b.textContent ? 1 : -1;
                });
                divArr.forEach(function (p) {
                    wrap.appendChild(p);
                });
            });
        </script>
    </head>
    <body>
        <div id="wrap">
            <div>Q</div>
            <div>W</div>
            <div>E</div>
            <div>R</div>
            <div>T</div>
            <div>Y</div>
            <div>U</div>
            <div>I</div>
            <div>O</div>
            <div>P</div>
            <div>A</div>
            <div>S</div>
            <div>D</div>
            <div>F</div>
            <div>G</div>
            <div>H</div>
            <div>J</div>
            <div>K</div>
            <div>L</div>
            <div>Z</div>
            <div>X</div>
            <div>C</div>
            <div>V</div>
            <div>B</div>
            <div>N</div>
            <div>M</div>
        </div>
    </body>
</html>

 

标签:function,document,DOM,JavaScript,divArr,var,wrap,div,排序
来源: https://www.cnblogs.com/noorty/p/16584793.html