0

I have a page with textbox with attribute value as "Original Value". Let us assume I have loaded it and typed "New Value" in the textbox. Both examples below should return -1 (I tried it in Firefox console).

// 1.
var wholecontento = "";
var wholecontento = document.documentElement.outerHTML;
alert(wholecontento.search("New Value"));

// 2.
var wholecontento = "";
var wholecontento = document.body.outerHTML;
alert(wholecontento.search("New Value"));

But both of them return integer larger than 1. How can I fix it?

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
Dhay
  • 585
  • 7
  • 29
  • Is it safe to perform a second request to the server? – Paul S. Nov 12 '15 at 04:52
  • Yes. It is safe. But I should get the current content to evaluate. – Dhay Nov 12 '15 at 04:55
  • 1
    Performing another request is the only way to get source which hasn't been parsed & interpreted, possibly dynamically modified, and then re-serialised. If you're okay with it being re-serialised but don't want user interaction, use your favourite DOM serialisation method at _DOMContentLoaded_ time and store this somewhere for your future lookup – Paul S. Nov 12 '15 at 04:57

1 Answers1

1

It is a correct behaviour. You getting the HTML string using DOM (Document Object Model), which reflects the current HTML page you are seeing in the browser (including whatever changed)

If you need to retain the old value of the text box, you need to:

  1. Either, store the original value of the textbox upon page loaded for comparing later
  2. Or, only if you need the real HTML source code, you can do either:
    1. Make sure your code is the first bit of code run by the browser, it might be tricky to get a cross-browser solution (have a look at this question), then in your code, store a copy of the document.body.outerHTML for later use.
    2. Or, initiate a request back to the current URL and store the return body as HTML source code, this way you are sure that you have a copy of the original HTML source code, but it costs you 1 additional request.

//jQuery code
$.get(window.location.href, function (resp) {
     // store the resp.data on some object
     var sourceHTML = resp.data;
 })
 .fail(function (resp) {
     // error handling
 });

Added comment of Paul S below

The document.body.outerHTML will contain only the <body> section. This (new XMLSerializer).serializeToString(document) will give you the whole <html>, including the <!DOCTYPE html>

Community
  • 1
  • 1
Mr. Duc Nguyen
  • 1,049
  • 7
  • 16
  • 2
    You can also run `(new XMLSerializer).serializeToString(document)` instead of using _outerHTML_. This will include things such as the ` ` – Paul S. Nov 12 '15 at 05:45