将元素添加到更多标记(=>仅添加第一个元素)

时间:2016-12-19 14:39:11

标签: javascript jquery html append appendchild

function $(selector) {

    var resultObject = {
        append: function (element) {
            var parser = new DOMParser();
            var dos = parser.parseFromString(element, "text/html");

            var all = dos.getElementsByTagName("body")[0];
       

            var elemWhichAppend = document.getElementsByClassName("testing");

            var children = all.childNodes;


            for (var i = 0; i < elemWhichAppend.length; i++) {
                
                var msgContainer = document.createDocumentFragment();
                var children = all.childNodes;

                for (var child = 0; child < children.length; child++) {
                
                    var al = myLo(children[child]);
                    msgContainer.appendChild(al);
                }
                insertAfter(msgContainer, elemWhichAppend[i]);
            }
            



        }
    }
    return resultObject;
}

function insertAfter(newNode, referenceNode) {
    referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
}

function myLo(curElem)
{

    var whichnodetype;

    if (curElem.nodeType == 3)
    {
        whichnodetype = document.createTextNode(curElem.nodeValue);
    }
    else
    {
        var whichnodetype = document.createElement(curElem.nodeName);
    }

    var children = curElem.childNodes;
    for (var child = 0; child < children.length; child++) {
        whichnodetype.appendChild(children[child]);
    }

    return whichnodetype;
}
<!DOCTYPE html>
<html>
<head>
    <title></title>
	<meta charset="utf-8" />
</head>
<body>
    <h1 class="testing">APPEND</h1>
    <p>Hallo, ich bin ein P TAG </p>
    <h2 class="testing">APPEND2</h2>
    <input type="button" value="append tag/text " onclick="$('.testing').append('<ul><li>RIBA RIBI<ul><li>FRANK RIBERY</li></ul></li></ul> <h1>NIGOGOG</h1> messi ist scheiße');" />
</body>
</html>

我设法将每个元素添加到第一个标记,但第二次只添加最后一个标记。请参阅代码剪切。它每次循环两次,这是正确的,但第二次仍然不正确。

1 个答案:

答案 0 :(得分:0)

我对你如何解决这个问题感到困惑,为什么你用自己的版本替换append,但作为如何在代码的一小部分中使用jQuery追加多个目标的例子:

JSFiddle:https://jsfiddle.net/TrueBlueAussie/ad2qf4uy/

$('.addbutton').click(function(){
    $('.testing').append('<ul><li>RIBA RIBI<ul><li>FRANK RIBERY</li></ul></li></ul> <h1>NIGOGOG</h1> messi ist scheiße');
});

如果你能解释你的目标是什么,这会让生活变得如此简单:)