0

In a lot of what I'm reading about Javascript the examples show how to edit a given element by first getting its object using document.getElementById(). However I've seen other code where this isn't used and the element's Id is just used directly.

<!DOCTYPE html>
<html lang="en">

<head>

  <script>
    function test1(){
      document.getElementById("paragraph").innerHTML = "test 1 works";
    }

    function test2(){
      paragraph.innerHTML = "test 2 works";
    }
  </script>

</head>

<body>

<a href="#" onClick="test1()">Run Test 1</a>
<a href="#" onClick="test2()">Run Test 1</a>

<p id="paragraph"></p>

</body>

</html>

Both test1() and test2() are able to update the innerHTML of the 'paragraph' element. However the first one uses document.getElementById(paragraph) and the second one skips this and just uses the Id itself.

Since both of these work is there a preferred method? Does it depend on the browser?

RobG
  • 142,382
  • 31
  • 172
  • 209
Bob
  • 9
  • 2
  • 1
    preferred method is `getElementById` because some id's wont work with the second method, e.g. try adding `var paragraph;` at the top of your script – Jaromanda X Oct 14 '15 at 22:54
  • 3
    Refer to this question http://stackoverflow.com/questions/3434278/do-dom-tree-elements-with-ids-become-global-variables – santon Oct 14 '15 at 23:01

0 Answers0