开发者

How to append an Object to a DOM Element with JQuery append(), add() or appendTo()?

I can't seem to get this working, even though I have the idea it is perfectly correct. Consider the following code:

<script type="text/javascript>
        ul = $(".qtrans_language_chooser");
        p开发者_如何学运维arent = ul.parent();
        activeLangLi = ul.children("li.active");

        parent.prepend('<ul class="qtrans_active_language"></ul>');
        activeLangUl = $(".qtrans_active_language");
        o = activeLangLi.appendTo(activeLangUl);
        activeLangLi.remove();
</script>

All I'm trying to do is add activeLangLi to the empty activeLangUl. But no matter if I use append(), appendTo() or add() it never shows up.


Remove this line:

activeLangLi.remove();

This removes the elements from the DOM. append and appendTo will move (not copy) the elements from the current location to the new one. If you remove them afterwards, well, then they are gone.

You could also optimize your code to:

var ul = $(".qtrans_language_chooser");
$('<ul class="qtrans_active_language"></ul>')
    .prependTo(ul.parent())
    .append(ul.children("li.active"));

Don't forget to use var.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜