Sunday, June 2, 2024
 Popular · Latest · Hot · Upcoming
55
rated 0 times [  57] [ 2]  / answers: 1 / hits: 30986  / 8 Years ago, mon, march 28, 2016, 12:00:00

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);

More From » jquery

 Answers
27

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>




[#62777] Saturday, March 26, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jazminuniquer

Total Points: 63
Total Questions: 121
Total Answers: 96

Location: Cambodia
Member since Thu, May 21, 2020
4 Years ago
;