0

This is the jQuery code

success: function (html) {
         var text = $(html).text();
         if (text == '') {
            location.reload();
         } else {
            $("#warning2").html(html);

         }
 }

What I want is to convert $(html).text(); to plain JavaScript

Here is my plain JavaScript code but the page will not reload unlike jQuery code.

xhttp.onreadystatechange = function() 
{
    if (xhttp.readyState == 4 && xhttp.status == 200)
       {
       if (xhttp.responseText == "" || xhttp.responseText.textContent == "")
         location.reload();
       else
         document.getElementById("warning2").innerHTML = xhttp.responseText;
      }
};
Fullstack Guy
  • 16,368
  • 3
  • 29
  • 44
nothingn
  • 1
  • 2
  • 1
    Possible duplicate of [Is there an easy way to convert jquery code to javascript?](https://stackoverflow.com/questions/978799/is-there-an-easy-way-to-convert-jquery-code-to-javascript) – Heretic Monkey Sep 15 '18 at 02:02
  • In this case, it's because the jQuery is parsing the HTML returned, then finding if there's any text within the elements parsed, whereas the JavaScript is testing if there's any HTML returned. To parse the HTML in plain JavaScript, see https://stackoverflow.com/q/32250434/215552. – Heretic Monkey Sep 15 '18 at 02:05

1 Answers1

0

Based on your description:

"What I want is to convert $(html).text(); to plain JavaScript"

So, I suppose you have a correct ajax function and your question is about converting that part of your code to pure js. (If you haven't it, you can check stackoverflow for links like this ).

Your code in jquery:

var text = $(html).text();

Same code in js:

var uDiv=document.createElement("div");
uDiv.innerHTML= xhttp.responseText;
var text=uDiv.children[0].innerText; //or .innerHTML

tip: in your last line (.innerHTML=...), if the response has script tags, you must separate them and create that script tags via code (similar my above code).

Hassan Sadeghi
  • 1,316
  • 2
  • 8
  • 14