I'm using the Embedded Tweets API from Twitter. 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:
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!
EDIT:
As of July 28th 2015, the getElementsByClassName
example has been removed from Twitter's documentation thanks to another post I made on the Twitter Dev Forums
I'm using the Embedded Tweets API from Twitter. 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./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!
EDIT:
As of July 28th 2015, the getElementsByClassName
example has been removed from Twitter's documentation thanks to another post I made on the Twitter Dev Forums
2 Answers
Reset to default 3 +50The problem may e from the fact that document.getElementsByClassName
returns a NodeList
type which is not real javascript Array
object. On the other hand, widgets.load
expects either a single element or an Array
of elements. This leads nodeList to be treated as a single element and the library tries to call querySelectorAll
on it which is not available for NodeList
types.
A solution would be to convert that nodeList to a real array when passing it to widgets.load.
One way:
twttr.widgets.load(
Array.prototype.slice.call(document.getElementsByClassName("containers"))
);
This works, because a NodeList has a length
property and is indexable.
According to twitter's documentation, load()
accepts either no param or a single element.
Called without argument, widgets-js will search the entire document.body DOM tree for uninitialized widgets. For better performance, pass an HTMLElement object to restrict the search only to children of the element.
Since getElementsByClassName
returns an HTMLCollection
, you can't pass that directly. Instead you could pass the first element in the collection like this
twttr.widgets.load(
document.getElementsByClassName("containers")[0];
);