I have a form with three different inputs; two text and one submit. The html for this form is stored in a javaScript variable var form. When the user clicks a button, the following code is executed:
$('#content').html(form);
This works as expected. Then, when the user clicks the button again, it compares the html of the #content element with var form. You would expect it to return true since I just set the element to contain the contents of form, yet it returns false.
I found that when I retrieve the html from the #content element, it’s slightly different than it was when I inserted it. For each of the input tags, the type attribute is moved from the beginning to the end. That is:
<input type="text"... /> --> <input ...type="text" />
So understandably when I try to compare them, it returns false. However, that begs the question of why it isn’t inserting the html exactly as it is in the variable?
This is likely not due to jQuery; this is the browser. Once text/html is turned into DOM nodes, turning those nodes back into text is browser-dependent and not defined by a spec.
If you want to compare if the contents of the
<form>tag are the same as when you created it you can’t compare its text form. After all,<form class="foo" id="bar">and<form id="bar" class="foo">would yield identical DOM nodes once parsed by a browser.You should compare only the attributes you expect to change and have well-defined states, like the
valueof input elements.