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>
document.querySelector('audio')which selects the first audio element on the page. Note that you are currently passing the returned value of theaudiofunction as theonloadhandler. Set it without calling it yourself!audio(), and whatever that returns is then put intowindow.onload. This only makes sense ifaudio()returns a function object.<audio>) is removed in this example jsfiddle.net/c8zdfhpy then an error occurs: "Uncaught TypeError: Cannot read properties of undefined (reading 'paused')". By adding the if statement, I thought the javascript audio(); function would run "only if" such an<audio>element exist on a page.