MutationObserver: new value in the format of `oldValue`
Attributes and properties are different things. To get the attribute string, you'd use getAttribute
:
newValue = mutation.target.getAttribute(mutation.attributeName);
You were accessing the property from the element instance, which in the case of style
is a CSSStyleDeclaration
object reflecting the parsed style properties from the style
attribute. While many attributes are reflected directly as properties (id
, name
), others are in a different form (like style
) or aren't available as properties on the element at all.
Mutation observer event new value
You can simply query current value directly from the changed object.
// is element is an input
const newValue = document.getElementByID('myElement').value;
// or, if it is a any text element
const newValue = document.getElementByID('myElement').innerHTML;
Also, each MutationRecord
have a property named target
which contains all detailed information about changed object. So depending on MutationRecord.type
(which tells us what type of the change have happened) you can get new value from corresponding property inside MutationRecord.target
Use MutationObserver compare old and new text content
Are you required to use Mutation Observer? Or is OK to use a global variable?
There are so many ways to do it... Bellow is the fastest solution. I can update it based on your feedback, therefore feel free to ask me anything in Comment section.
The simplest way to keep track of previous value is to save it all the time at the end of processing function.
In the example bellow, at the end of changeButton
function, I just updated previousValue to be equal with newValue.
When the page initial loads, previousValue is equal with currentValue.
// global variableconst changeBtn = document.getElementById('changeButton');const target = document.getElementById('changingElement');
// Save previous_value in a data attribute, if global variables are not an optiontarget.dataset.previousValue = parseInt(target.innerText);
changeBtn.addEventListener('click', function(e){
let previousValue = target.dataset.previousValue currentValue = parseInt(target.innerText), newValue = currentValue + 1; target.innerText = newValue; console.log('ClasicWay: previous value is ' + previousValue); console.log('ClasicWay: new value is ' + newValue); // all processing ended at this point, // so we can update or previousValue to currentValue target.dataset.previousValue = currentValue;})
// Observer wayconst observer = new MutationObserver(function(mutations) { mutations.forEach(function(mutation) { console.log("MutationObserverWay: previous value is ", mutation["removedNodes"][0]["nodeValue"]); console.log("MutationObserverWay: new value is ", mutation["addedNodes"][0]["nodeValue"]); });});
observer.observe( target, { childList: true, });
.button { border: 1px solid black; font-weight: normal; margin-bottom: 10px; padding: 10px; width: fit-content;}.button:hover { font-weight: bold;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="changeButton" class="button"> Click me to change value</div>
<div id="changingElementParent"> <div> <div id="changingElement">100</div> </div></div>
Is MutationRecord.oldValue something I should be using?
Configure your observer with:
observer.observe(container, {
attributeOldValue : true
});
Full API documentation:
https://developer.mozilla.org/pt-BR/docs/Web/API/MutationObserver
Extracting specific information (position) from OldValue using MutationObserver
You can split you string and get what you need.
var alertValueSplit = mutation.oldValue.split("top:")
var topValue = alertValueSplit[1]
Detect input value change with MutationObserver
To understand what is going on is necessary to clear up the difference between attribute (content attribute) and property (IDL attribute). I won't expand on this as in SO there are already excellent answers covering the topic:
- Properties and Attributes in HTML
- .prop() vs .attr()
- What is happening behind .setAttribute vs .attribute=?
When you change the content of a input
element, by typing in or by JS:
targetNode.value="foo";
the browser updates the value
property but not the value
attribute (which reflects the defaultValue
property instead).
Then, if we look at the spec of MutationObserver, we will see that attributes is one of the object members that can be used. So if you explicitly set the value
attribute:
targetNode.setAttribute("value", "foo");
MutationObserver will notify an attribute modification. But there is nothing like properties in the list of the spec: the value
property can not be observed.
If you want to detect when an user alters the content of your input element, the input
event is the most straightforward way. If you need to catch JS modifications, go for setInterval
and compare the new value with the old one.
Check this SO question to know about different alternatives and its limitations.
Related Topics
IE9: Why Setting "-Ms-Transform" Works from CSS, But Not with Jquery.Css()
Jquery Mobile Prevent Scroll-To-Top Before Page Transition
Changed Id Not Being Found by Jquery
How to Check for Null Values in JavaScript
Download JSON Object as a File from Browser
JavaScript Function to Convert Color Names to Hex Codes
How to Import Jquery Using Es6 Syntax
$ Variable (Dollar Sign) in Chrome
Bootstrap and Jqueryui Conflict
How to Use Materialize-CSS with Angular
IE8 V8 Not Changing Class for a Dom Element Despite Js Function Changing the Element Attribute
JSON Datetime Between Python and JavaScript
Rendering Raw HTML with Reactjs