Uncaught TypeError: t.querySelectorAll is not a function

embeddedtweet

#1

I’m using the Embedded Tweets API.
Everything works great if I have the html markdown from page load.
It also works great if I use the option to add content later, and load the tweets by ID:

twttr.widgets.load(
  document.getElementById("container")
);

This is in the documentation here: https://dev.twitter.com/web/javascript/initialization#init

But If I try to load the tweets by class name with this:

twttr.widgets.load(
  document.getElementsByClassName("containers")
);

I’m getting this error inside Twitter’s widget.js:

Uncaught TypeError: t.querySelectorAll is not a function

If I log the group of elements to the console, I have a proper group:

Am I doing something wrong or is this a bug on Twitter’s widget?

Thanks!


#2

You’re passing twttr.widgets.load a collection of elements whereas it expects a single element. Either pass in a common parent of all the .containers elements or do something like this:

var containers = document.getElementsByClassName("containers");
containers = [].slice.call(containers, 0); // HTMLCollection to Array
containers.forEach(function(el) {
  twttr.widgets.load(el);
})

#3

I haven’t tried it yet, and will get back to you when I do, but if that is the case, the docs should really be updated, as the example you see here: https://dev.twitter.com/web/javascript/initialization#init

says to do it like

twttr.widgets.load(
  document.getElementsByClassName("containers")
);

Thanks for the fast response!! I’ll be back in a while with my results.


#4

FWIW it’s worth, the only example I see on that page is the following one and it uses getElementById (which returns a single element) and not getElementsByClassName (which returns a HTMLCollection).

twttr.widgets.load(
  document.getElementById("container")
);

If there’s another code snippet somewhere that I’m not seeing, let me know and I’ll make sure it’s updated accordingly.


#5

As Jake says, the example uses getElementById to return a single element, rather than a NodeList which the current release doesn’t handle. The input should take proper arrays though, so if you convert the input to a regular Array it will work.

I appreciate this is confusing though, and a forthcoming release of widgets-js will rectify this and handle NodeLists as well as Array for load(). Thanks for flagging it!

Ben


#6

Ha!! Apparently someone already fixed the documentation, nice job!

I should’ve taken a screenshot, now everyone is going to think I’m crazy. :smiley: But I took the getElementsByClassName example directly from that URL. Otherwise I would’ve never tried this, and post it here.

Thanks everyone for your help!!


#7