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>
5
  • 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! Commented May 20, 2022 at 22:33
  • Conditionally adding functions like this seems like a pretty strange thing to want to do. Can you clarify why you believe this is the best solution for whatever problem you're facing? Commented May 20, 2022 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. Commented May 20, 2022 at 22:41
  • @ggorlen Ram and Peter B Thank you for your comments. Reasing being that when the first line of HTML (containting <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. Commented May 22, 2022 at 10:15
  • Does this answer your question? JavaScript get element by name Commented May 22, 2022 at 16:05

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Excellent thank you. This solved the problem! The element got selected even without any (unique) id's!

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.