The main purpose of Javascript was to make web more Dyanamic. So accesing the DOM was very important. Lets learn the Diffrent ways used in Javascript to Access the DOM.

I hope we already know what a DOM is, it stands for Document Object Model. Its the structure of the HTML file Elements.

DOM Structure
DOM Structure

This Structure represents the parent and child structure in which the elements reside.

To call a DOM we need to initially call the Document. This is done by using the keyword ‘document’

document.getElementsByTagName(p).innerHTML("JS Text");  
// This commands calls all P elements within a document.
// and adds the Text 'JS Text' to it

Give it a try, Within HTML write the above code within a script tag. Check below example.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Test</title>
  </head>
  <body>
    <div class="test">
      <p></p>
      <p></p>
      <p></p>
    </div>
    <script type="text/javascript">
      // Always javascript must be written in here below
      // within a script tag placed last in Body code
      document.getElementsByTagName(p).innerHTML("JS Text");
      // This commands calls all P elements within a document.
      // and adds the Text 'JS Text' to it
    </script>
  </body>
</html>

Hence document keyword must be appended to access the DOM structure. More Commands are

document.getElementByID('IdName');
document.getElementsByClassName('className');
document.createElement(p);
document.appendChild(p);
document.write("This is a Text");

Advertisements