[Solved] Difference between getElementById and createElement in javascript? [closed]


The main difference is that getElementById will get an element from the DOM by it’s ID attribute, and createElement will create an entirely new DOM element.

Let’s say you had a page with the following HTML:

<!doctype html>

<html>
  <head>
  </head>

  <body>
    <div>Hello, World!</div>
    <div id="message">What a nice day!</div>
  </body>
</html>

And then you had some JavaScript code like so:

document.getElementById("message")

You will retrieve the <div> element that has an id attribute of "message".

Now, let’s say you wanted to add a new element to your HTML page, then you’d use the createElement function.

var newEl = document.createElement("div")

Of course, from the example, we are also storing the new element in a variable called newEl.

Now, to actually append the new element, we’d have to call appendChild on any DOM element. For the sake of simplicity, we’re going to simply append to the <body> tag.

document.body.appendChild(newEl)

Now, your page should (at least in the mind of the browser) look like so:

<!doctype html>

<html>
  <head>
  </head>

  <body>
    <div>Hello, World!</div>
    <div id="message">What a nice day!</div>
    <div></div>
  </body>
</html>

0

solved Difference between getElementById and createElement in javascript? [closed]