0

Hello this might be a stupid question but what is the point in the document.GetElementById function when you can just select the element like so:

<html><body>
<p id="sampletext">I am the sample</p>

<script>
sampletext.innerHTML="I have just been changed" //This changes the inner HTML
</script>
</body></html>

Please let me know if I'm missing something really obvious. Thanks.

  • 1
    If this works for you, go for it. – Gerard Dec 14 '20 at 22:06
  • 2
    Afaik, things like this remain for backwards compatibility reasons. – Taplar Dec 14 '20 at 22:09
  • 1
    What if you want to select a button, and add an even listener? – BlackMath Dec 14 '20 at 22:09
  • 4
    Possible duplicate. https://stackoverflow.com/questions/14478102/why-use-document-getelementbyid-when-i-can-directly-refer-to-the-dom-id-in-javas – eag845 Dec 14 '20 at 22:11
  • I didn't know of this, actually seems really useful. I just advise you to check it works on different browsers and to make sure you don't name other variables equally (which is the only reason I would see it not being widely accepted) – Fabio Lopez Dec 14 '20 at 22:11
  • 4
    @FabioLopez don't do it..... – epascarello Dec 14 '20 at 22:12
  • eag845 thanks for that it clarified it completely. I tried searching for a similar question to mine to see if there were any duplicates beforehand but I didn't succeed. – DGWebDevelopment Dec 15 '20 at 23:27

0 Answers0