1

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>
Sam
  • 15,254
  • 25
  • 90
  • 145
  • 1
    Use `document.querySelector('audio')` which selects the first audio element on the page. Note that you are currently passing the returned value of the `audio` function as the `onload` handler. Set it without calling it yourself! – Ram May 20 '22 at 22:33
  • Conditionally adding functions like this [seems like a pretty strange thing to want to do](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem/233676#233676). Can you clarify why you believe this is the best solution for whatever problem you're facing? – ggorlen May 20 '22 at 22:36
  • Agree with Ram. To clarify, what you do is call `audio()`, and *whatever that returns* is then put into `window.onload`. This only makes sense if `audio()` returns a **function** object. – Peter B May 20 '22 at 22:41
  • @ggorlen Ram and Peter B Thank you for your comments. Reasing being that when the first line of HTML (containting ` – Sam May 22 '22 at 10:15
  • Does this answer your question? [JavaScript get element by name](https://stackoverflow.com/questions/10306129/javascript-get-element-by-name) – Heretic Monkey May 22 '22 at 16:05

1 Answers1

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

Should do the work.

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

Nimarel
  • 317
  • 2
  • 2
  • Excellent thank you. This solved the problem! The element got selected even without any (unique) id's! – Sam May 22 '22 at 16:46