I am very frustrated today to select top div in sidebar of the twitter search page. I can do it in chrome dev tools, but it returns null or undefined when using tamper monkey. can anyone help me out?
// ==UserScript==
// @name twitter
// @namespace http://tampermonkey.net/
// @version 0.1
// @description try to take over the world!
// @author You
// @match https://twitter.com/*
// @run-at document-end
// @icon https://www.google.com/s2/favicons?sz=64&domain=twitter.com
// @grant none
// ==/UserScript==
(function() {
'use strict';
let container = document.querySelector(".css-1dbjc4n.r-vacyoi.r-ttdzmv");
console.log(container);
})();
Thanks to @wOxxOm, I did some research and find out these codes work. from here
let classes = ".css-1dbjc4n.r-vacyoi.r-ttdzmv";
function isElement(addedNode, selector, callback) {
if (typeof addedNode.querySelector === 'function' && addedNode.querySelector(selector)) {
callback();
}
}
var elementReadyObserver = new MutationObserver(function (mutations) {
for (var i=0, numMutations=mutations.length; i<numMutations; i++) {
for (var j=0, numNodes=mutations[i].addedNodes.length; j<numNodes; j++) {
isElement(mutations[i].addedNodes[j], classes, function() {
elementReadyObserver.disconnect();
// ... and do what you want to do with the element you've been observing
console.log("i found it");
let parentDiv = document.querySelector(classes);
console.log(parentDiv);
parentDiv.insertBefore(newDiv,parentDiv.firstChild);
});
}
}
});
elementReadyObserver.observe(document.body, {attributes: true, subtree: true, childList: true});