Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[2019-03-03]: appendChild() #12

Open
Lemonreds opened this issue Mar 3, 2019 · 0 comments
Open

[2019-03-03]: appendChild() #12

Lemonreds opened this issue Mar 3, 2019 · 0 comments

Comments

@Lemonreds
Copy link
Owner

前言

今天看到了一段代码,打破了自己以往对appendChild方法的看法。

具体代码

let fragment = document.createDocumentFragment()
let div = document.getElementById('app')

let child = div.firstChild
while(child){  
    fragment.appendChild(child)
    child = div.firstChild
}

代码的作用是创建一个fragment片段,然后将id为app的元素的所有子结点,包括文本结点、元素结点等,都复制到片段内。

值得注意的是,之前一直以为appendChild方法是不改动原有结点结构的,事实上,它会将被添加的结点从原有DOM树上删除,这也是上述代码中 div.firstChild生效的原因。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant