Herelo
Herelo

Reputation: 119

Convert jQuery code to native Javascript

if I would convert my jQuery code into Javascript version. I've two pages: page.html and side.html The page.html take the div id and content from side.html document. It works very fine, but I prefer don't use jQuery for my project. How I can modify my code to native Javascript?

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
 <head>
  <title>Useless</title>
  <script type='text/javascript' src='jquery-3.1.1.min.js'></script>
 </head>
 <body>
   Hello
   <script type="text/javascript">
      jQuery.ajax({
              url: "side.html",
              success: function(result) {
                var html = jQuery('<div>').html(result);
                  alert(html.find("div#a").attr("id"));
                  alert(html.find("div#a").html());
                  alert(html.find("div#b").attr("id"));
                  alert(html.find("div#b").html());
             },
         }); 
  </script>
 </body>
</html>

I write this code, but it doesn't work :(

var html = new XMLHttpRequest();
 html.open("POST","side.html", true);
 success: function(result) {
 var html = ('<div>').html(result);
  alert(html.find("div#a").attr("id"));
  alert(html.find("div#a").html());
  alert(html.find("div#b").attr("id"));
  alert(html.find("div#b").html());
}

Upvotes: 0

Views: 2877

Answers (1)

user1106925
user1106925

Reputation:

From your attempt, it seems you may be thinking that the jQuery and native API's are nearly identical. They're not, so quite a few more changes are needed.

Note the comments in the code below. Also note that I removed the alert calls and used console.log instead, so be sure to open the developer console.

// Create and open the XHR object
var xhr = new XMLHttpRequest();
xhr.open("POST","side.html", true);

// Attach an event handler that fires when the requested content has loaded
xhr.addEventListener("load", function(result) {
  var d = document.createElement('div'); // Create a new element
  d.innerHTML = xhr.responseText;        // Add the response text

  var a = d.querySelector("#a"); // Fetch the `a` element
  var b = d.querySelector("#b"); // Fetch the `b` element

  console.log(a.id, a.innerHTML); // Display the id and content of each
  console.log(b.id, b.innerHTML);
});

xhr.send();

It's pretty common to have a small collection of utilities to reduce redundant code. There's not much needed here, but in general it's not a bad idea to have functions to shorten the DOM selection and creation methods a little.

Upvotes: 3

Related Questions