0

I made this in jquery and it works fine,
but I need to make it in pure javascript.

The following code doesn't works, I don't understand why...
I'm not expert in javascript...

function playVideo() {
    var popo = document.getElementsByTagName("object");
    popo.forEach(function(index){ 
          var obj = this.get(0);
          obj.playVideo(); 
    });
}

Update: I will try to post my workin jquery version

function pauseVideo() {
    $("object").each(function(index){ 
          obj = $(this).get(0);
          obj.pauseVideo(); 
    });
}

2 Answers 2

0

document.getElementsByTagName returns a nodeList, and even though it's array-like, it doesn't have array methods like forEach, some, every etc. so you have to iterate the old fashion way

function playVideo() {
    var popo = document.getElementsByTagName("object");
    for (var i=0; i<popo.length; i++) {
        popo[i].playVideo(); 
    }
}
Sign up to request clarification or add additional context in comments.

12 Comments

doesn't work for my code... maybe I must post my jquery working jquery?
I was wondering what get() was doing, but I suspect you're trying to use jQuery methods on DOM nodes, and if you're using jQuery, why on earth would be doing it this way to begin with ?
Yeah, not sure I get it, what is playVideo and pauseVideo and how are those methods chainable to plain DOM nodes ?
Are you sure it shouldn't be $(popo[i]).playVideo(); and that playVideo is a jQuery plugin ?
You're going to have to explain this a lot better. You have a function called playVideo, it's the one in the code above, but what are you expecting when you do obj.playVideo(), what function do you have with that name that can be chained onto a native DOM node. Where are you getting element.playVideo() from ?
|
0

Because selector functions like getElementsByTagName return NodeList objects, and not Array objects.

Two fixes:

  • manually convert to array: yesArray = [].slice.call(noArray) so you can yesArray.forEach(...
  • add forEach to NodeList: NodeList.prototype.forEach = [].forEach

I like the second, but it's not 'correct' according to some:

// Somewhere in your lib:
NodeList.prototype.forEach = [].forEach;

// In app code:
var popo = document.getElementsByTagName("object");
popo.forEach(function(index) {
  .. etc
});

8 Comments

Maybe it's nicer to do Array.slice.call instead of [].slice.call? I think it's a little clearer.
@jaapz - The proper way would be Array.prototype.slice.call()
Array.slice is a function? You might mean Array.prototype.slice, which is way too much to type.
@adeneo 'proper' =) I like that.
Yeah, typo, that's what i meant :) I think code clarity beats 'typing a lot'.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.