1

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&amp;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&amp;w=336&amp;h=188&amp;stc=true&amp;jpg444=true&amp;jpgq=90&amp;sp=68&amp;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:

  1. Get a handle to that <img> element. (It will be the only image element in the chunk of HTML.)
  2. Get a handle to the <div> element that contains the data-context-item-id attribute. (In this particular case the value is Kky3wgURBJ0.)

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.

HerrimanCoder
  • 6,835
  • 24
  • 78
  • 158
  • Your doing something weird: why convert addedNodes to HTML if you can access it directly as DOM tree? – wOxxOm Dec 26 '16 at 21:29

1 Answers1

2

Can jQuery find elements in an arbitrary chunk of html as shown above?

Yes, it can. Here is an example.

// create a container for your html
var $div = $('<div>')

// inject html
$div.html(newHTMLChunk)

// traverse
$div.find('div[data-context-item-id="Kky3wgURBJ0"]')

Edit: this can also be done without jQuery, using DocumentFragment

See Inserting arbitrary HTML into a DocumentFragment

Community
  • 1
  • 1
posit labs
  • 8,951
  • 4
  • 36
  • 66