Faktor 10
Faktor 10

Reputation: 1878

What is the difference between calling the DOM method appendChild directly on document.body versus first using queryselector

Is there any difference to calling the following which both result in the same output?

// direct call
      const p = document.createElement('p')
      p.innerHtml = 'I am a p tag' 
      document.body.appendChild(p)

// first querySelector then method call
      const p = document.createElement('p')
      p.innerHtml = 'I am a p tag' 
      const body = document.querySelector('body')
      body.appendChild(p)

Upvotes: 0

Views: 54

Answers (1)

charlietfl
charlietfl

Reputation: 171679

There is no functional difference since both approaches to access the body return the same object. From a performance stand point document.body is most likely faster but I highly doubt the difference is significant enough to suggest not using querySelector

There are numerous ways to access the same dom element

const el = document.querySelector('body')

console.log(el === document.body) //true
console.log(el === document.getElementsByTagName('body')[0]) // true

Upvotes: 2

Related Questions