JSFiddle - React, Tailwind, and code Playground
by pxfunc
HTML
<div>
<input type="text" /><button class="setValue">set via JS</button>
</div>
<div>
<textarea></textarea><button class="setValue">set via JS</button>
</div>
CSS
div {
margin: 10px;
}
JavaScript
// select the target node
var targets = document.querySelectorAll('input, select, textarea');
Array.prototype.forEach.call(targets, function(target) {
// create an observer instance
var observer = new MutationObserver(function(mutations) {
console.log(mutations);
mutations.forEach(function(mutation) {
console.log(mutation.type);
});
});
// configuration of the observer:
var config = { attributes: true, childList: true, characterData: true };
// pass in the target node, as well as the observer options
observer.observe(target, config);
// later, you can stop observing
//observer.disconnect();
});
var buttonsSetValue = document.querySelectorAll('.setValue');
Array.prototype.forEach.call(buttonsSetValue, function(button) {
button.addEventListener('click', function() {
var input = this.previousSibling;
if (input.tagName === 'TEXTAREA') {
input.innerText = 'test';
} else {
input.setAttribute('value', 'test');
}
});
});