Home > database >  Can JavaScript function trigger only when specific HTML <element> exist eliminating the need o
Can JavaScript function trigger only when specific HTML <element> exist eliminating the need o

Time:05-23

Unlike questions based on (unique) id's and name's, this targets name-less and id-less elements!


I would like to load the JavaScript function called audio() only when an <audio> element is present on the HTML page.
If there is such an HTML element, then there would be only 1 instance of this <audio> element on the entire HTML page.

At the moment I'm selecting a unique id (audio) which works.

I wonder however, would it be possible to omit the id="audio" and just let the if statement trigger on the very existence of the <audio> html element on the page. If yess, then what if-statement would safely trigger a positive when such an <audio> HTML-element exist?

JS

if (document.getElementById("audio") !== null){
    window.onload = audio();
}

HTML

<audio id="audio" src="/audiofile.mp3" type="audio/mpeg" preload="none"></audio>

CodePudding user response:

if (document.getElementsByTagName("audio").length !== 0){
  window.onload = audio();
}

Should do the work.

From: https://developer.mozilla.org/fr/docs/Web/API/Document/getElementsByTagName

  • Related