so my code below works stand alone in a jsfiddle. but for some odd reason.. I get this error consistently after pushing it to a live server :/ and I can't figure out why...
error:
mycodewitherror.js:23 Uncaught TypeError: Failed to execute 'observe' on 'MutationObserver': parameter 1 is not of type 'Node'.
js:
$(document).ready(function() {
// The below collects user login name, new login date and time, and previous use URL
var element = document.querySelector('.pet-name');
// create an observer instance
var observer = new MutationObserver(function(mutations) {
var username = $('.pet-name').text();
var referrer = document.referrer;
var date = new Date();
var month = date.getUTCMonth() + 1;
var day = date.getUTCDate();
var year = date.getUTCFullYear();
var time = date.toLocaleTimeString();
var formattedDate = month + '/' + day + '/' + year;
console.log("Pet Name Time");
console.log(referrer);
console.log(petname);
console.log(time);
console.log(formattedDate);
});
// 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(element, config);
I encountered the same error, and solved it by calling the .observe()
method inside the onload/ready
code-block instead of the observer var definition, plus the definition of target
element and config
variables:
Please run the code snippet below, click the "Add list item" button and watch the change log in the console.
$(document).ready(function () {
var target = document.getElementById("myList");
var config = {
childList: true,
subtree: true,
attributes: true,
characterData: true
};
//note this observe method call
observer.observe(target, config);
console.log("Observer is registered");
});
var observer = new MutationObserver(function (mutationRecords, observer) {
mutationRecords.forEach(function (mutation) {
console.log("mutation change in ", mutation.type, " name: ",mutation.target);
});
});
function add() {
var index = $("ul li").length;
var listItem = document.createElement("li");
listItem.textContent = index + 1;
var target = document.getElementById("myList").appendChild(listItem, "before");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body >
<button onclick="add()">Add list item</button>
<hr>
<ul id="myList">
<li><a href="#">1</a></li>
<li><a href="#">2</a></li>
</ul>
</body>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With