I'm using observable mutations inside a Chrome extension and it's working well:
var insertedNodes = [];
var observer = new MutationObserver(function (mutations) {
mutations.forEach(function (mutation) {
// loop through each chunk of html that changes on the page
for (var i = 0; i < mutation.addedNodes.length; i++){
newHTMLChunk = mutation.addedNodes[i];
//console.log(newHTMLChunk);
}
})
});
observer.observe(document, {
attributes: true,
childList: true,
characterData: true,
subtree:true
});
Inside each iteration (inside YouTube in this case), newHTMLChunk
evaluates to a chunk of HTML like the following:
<li class="channels-content-item yt-shelf-grid-item">
<div class="yt-lockup clearfix yt-lockup-video yt-lockup-grid vve-check" data-context-item-id="Kky3wgURBJ0" data-visibility-tracking="QJ2JxKig-K2mKg==">
<div class="yt-lockup-dismissable">
<div class="yt-lockup-thumbnail">
<span class=" spf-link ux-thumb-wrap contains-addto">
<a href="/watch?v=Kky3wgURBJ0" class="yt-uix-sessionlink" aria-hidden="true" data-sessionlink="ei=PkhhWMS-CoXMugKIxL_YDg&feature=c4-videos-u"> <span class="video-thumb yt-thumb yt-thumb-196">
<span class="yt-thumb-default">
<span class="yt-thumb-clip">
<img alt="" src="https://i.ytimg.com/vi/Kky3wgURBJ0/hqdefault.jpg?custom=true&w=336&h=188&stc=true&jpg444=true&jpgq=90&sp=68&sigh=PSGK-mxzthJQOk44ZEKdd1jCrkA" onload=";__ytRIL(this)" width="196" data-ytimg="1" aria-hidden="true">
...more here ...
Now what I'm trying to do is the following:
- Get a handle to that
<img>
element. (It will be the only image element in the chunk of HTML.) - Get a handle to the
<div>
element that contains thedata-context-item-id
attribute. (In this particular case the value isKky3wgURBJ0
.)
Can jQuery find elements in an arbitrary chunk of html as shown above? Or can it only operate on an entire web page? Thanks in advance for your help.