用纯JS包装像jQuery中的wrap()函数这样的元素

时间:2014-08-25 14:35:38

标签: javascript html dom

尝试将每个按钮包装在div中(class =' gp')。如何使用纯JavaScript实现这一点。

HTML

<div class="af-button-group af-button-group-justified">
    <button class="af-button af-button-lg af-button-danger">sds</button>
    <button class="af-button af-button-lg af-button-ok">sdsasas</button>
    <button class="af-button af-button-lg">sds</button>
</div>

CSS

.gp{
    background: blue;
    padding: 8px;
}

的JavaScript

function fixjsf(){
    var parent = document.getElementsByClassName("af-button-group-justified");
    var elementsCount = parent.length;
    for(var i=0; i<=elementsCount; i++){
        var childCount = parent[i].childNodes.length;
        var elementContent = "";
        for(var j=0; j<=childCount; j++){
            var clone = parent[i].childNodes[j].cloneNode(true);
            elementContent += "<div class='gp'>"+clone+"</div>";
        }
        parent[i].innerHTML = elementContent;
    }
}
fixjsf();

期待dom看起来像这样

<div class="af-button-group af-button-group-justified">
    <div class='gp'>
    <button class="af-button af-button-lg af-button-danger">sds</button>
    </div>
    <div class='gp'>
    <button class="af-button af-button-lg af-button-ok">sdsasas</button>
    </div>
    <div class='gp'>
    <button class="af-button af-button-lg">sds</button>
    </div>
</div>

JSFiddle

4 个答案:

答案 0 :(得分:4)

怎么样:

function fixjsf(){
    var parent = document.getElementsByClassName("af-button-group-justified");
    var elementsCount = parent.length;
    for(var i=0; i<elementsCount; i++){
        var children = parent[i].getElementsByTagName("button");
        for(var j=0; j < children.length; j++){
            var child = parent[i].removeChild(children[0]);
            var wrap = document.createElement("div");
            wrap.className = "gp";
            wrap.appendChild(child);
            parent[i].appendChild(wrap);
        }
    }
}

http://jsfiddle.net/7vhfvakL/7/

对于每个父项,我们获取其下的所有按钮(或者您可以按类名选择)然后我们删除每个子项,创建一个包装器div,将子项附加到包装器并将包装器附加回父项。

或者......你可以在jQuery中使用wrap函数。

答案 1 :(得分:3)

虽然你已经接受了答案,但我有一点时间,并且认为我会提供一个替代方案(希望它的功能类似于jQuery的wrap()):

NodeList.prototype.wrap = function (wrapper) {
    // creating a temporary element to contain the HTML string ('wrapper'):
    var temp = document.createElement('div'),
    // a reference to the parent of the first Node:
        parent = this[0].parentNode,
    // a reference to where the newly-created nodes should be inserted:
        insertWhere = this[0].previousSibling,
    // caching a variable:
        target;

    // setting the innerHTML of the temporary element to what was passed-in:
    temp.innerHTML = wrapper;

    // getting a reference to the outermost element in the HTML string passed-in:
    target = temp.firstChild;

    // a naive search for the deepest node of the passed-in string:        
    while (target.firstChild) {
        target = target.firstChild;
    }

    // iterating over each Node:
    [].forEach.call(this, function(a){
        // appending each of those Nodes to the deepest node of the passed-in string:
        target.appendChild(a);
    });

    // inserting the created-nodes either before the previousSibling of the first
    // Node (if there is one), or before the firstChild of the parent:
    parent.insertBefore(temp.firstChild, (insertWhere ? insertWhere.nextSibling : parent.firstChild));

}

// retrieving a selection of Nodes and calling the 'wrap()' method upon them:
document.querySelectorAll('button.af-button').wrap('<div></div>');

JS Fiddle demo

参考文献:

答案 2 :(得分:1)

使用innerHTML你可以..!

以下是Fiddle

我修改了js函数,如下所示

    function fixjsf() {
    var parent = document.getElementsByClassName("af-button-group-justified");
    var elementsCount = parent.length;
    for (var i = 0; i < elementsCount; i++) {
        var childCount = parent[i].childNodes.length;

        var elementContent = "";
        for (var j = 0; j < childCount; j++) {           
            if (parent[i].childNodes[j].nodeName == "BUTTON") {
                var clone = parent[i].childNodes[j].outerHTML;
                elementContent += "<div class='gp'>" + clone + "</div>";
            }
        }
        parent[i].innerHTML = elementContent;

    }
}

fixjsf();

答案 3 :(得分:0)

Node.replaceChild

的另一种变体
function fixjsf(){
    var parent = document.getElementsByClassName("af-button-group-justified");
    var elementsCount = parent.length;
    for(var i=0; i<elementsCount; i++){
        var childLen = parent[i].childNodes.length;
        for(var j=0; j<childLen; j++){
            var child = parent[i].childNodes[j];
            if(child instanceof HTMLElement){
                var wrap = document.createElement('div');
                wrap.className = 'gp';
                wrap.appendChild(child.cloneNode(true));
                parent[i].replaceChild(wrap,child);              
            }
        }
    }
}

JS Fiddle