Search code examples
javascriptdomcallhighslide

JS: Call a specific function of a given script-object


Is this possible?

myscripts = document.getElementsByTagName("script");
myscripts[0].init();

The Problem

i use highslide with several html-Windows (htmlExpand). Every have a script with a init()function. If one Window is opened, it's included init function should be called.

Because, there are now several init functions, i couldn't call it directly, because it call in most cases the wrong function.

hs.Expander.prototype.onAfterExpand = function (sender) {init()}

i have to call a function of a given script object

hs.Expander.prototype.onAfterExpand = function (sender) {
  var content = this.content.getElementsByClassName("highslide-maincontent")[0];
  var myscripts = content.getElementsByTagName("script");
  for (var i = 0; i < myscripts.length; i ++){
     if (typeof myscripts[i].init == "function"){
        myscripts[i].init();
   }
}

But how i could do it? This shouln't work.

myscripts[i].init();

So, how i could call a function of a given script-object


Solution

  • No this is not possible, because an HTMLScriptElement, returned by document.getElementsByTagName("script")[0] in your code block, does not have an init() method. Indeed it doesn't have any methods, nor does it inherit init() from its parents up the chain HTMLElement, Element, Node, or EventTarget.

    I think you are trying to expose the init() method on whatever JS objects are added in a particular script. But, you wouldn't do it that way. For that, you might want to look into something like: https://css-tricks.com/how-do-you-structure-javascript-the-module-pattern-edition/