Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript AJAX Basics Programming AJAX Check for the correct ready state

Using `querySelector('#sidebar')` instead of `getElementById('sidebar')

The challenge task 3 of 4 is forcing me to use the getElementById('sidebar') document method to select the div in question.

app.js
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
  if ( xhr.readyState === 4) { 
    // Server has sent back complete response.  
    if ( xhr.status === 200) { 
      // Server return status is okay (200).  
      // Add data to page.  
      sidebar = document.querySelector('#sidebar');  
    } 
  }
};
xhr.open('GET', 'sidebar.html');
xhr.send();
index.html
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>AJAX with JavaScript</title>
  <script src="app.js"></script>
</head>
<body>
  <div id="main">
    <h1>AJAX!</h1>
  </div>
  <div id="sidebar"></div>
</body>
</html>

1 Answer

HI!

In the real world, document.querySelector('#sidebar) should work just fine.

Sometimes the task test programs are not very flexible though...

This passes all four tasks:

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
  if ( xhr.readyState === 4) { 
    // Server has sent back complete response.  
    if ( xhr.status === 200) { 
      // Server return status is okay (200).  
      // Add data to page.  
     document.getElementById('sidebar').innerHTML = xhr.responseText;
    } 
  }
};
xhr.open('GET', 'sidebar.html');
xhr.send();

It's NOT part of the challenge, but I have recently learned that innerHTML can lead to serious XSS vulnerabilities (so in the real world use it cautiously).

More info:

https://gomakethings.com/preventing-cross-site-scripting-attacks-when-using-innerhtml-in-vanilla-javascript/

https://medium.com/front-end-weekly/javascript-innerhtml-innertext-and-textcontent-b75ec895cbe3

https://teamtreehouse.com/library/owasp-top-10-vulnerabilities

I hope that helps.

Stay safe and happy coding!