DOCUMENT OBJECT MODEL(DOM)

izzycious

Ishaq Nasir

Posted on June 27, 2022

DOCUMENT OBJECT MODEL(DOM)

INTRODUCTION TO DOM

When a web page is loaded, the browser creates a Document object model(DOM) of the page. which is the tree representation of an HTML document and the DOM tree is modified with JavaScript.

<table>
  <row>
    <tr>
      <td>......</td>
    </tr>
    <tr>
      <td>.....</td>
      <td>.....</td>
   </tr>
  </row>

</table>

Enter fullscreen mode Exit fullscreen mode

Alt Text

JavaScript And DOM

  1. JavaScript can add new HTML elements and attributes.
  2. JavaScript can change all the CSS styles in a page
  3. JavaScript can add and listen to HTML events like onScroll hover onclick, etc.
  4. JavaScript can change any HTML elements and attributes of a page.
  5. JavaScript can remove existing HTML elements and attributes.

Now, how do we add JavaScript to an HTML documents

<script> 
  console.log('active');
</script>
Enter fullscreen mode Exit fullscreen mode

checking your console, would prompt that it is active.

SELECTING HTML DOCUMENTS
This is when selecting HTML with JavaScript, and it provides a DOM method

    getElementById('targeted-html-doc');
Enter fullscreen mode Exit fullscreen mode

getElementById is a DOM method which accepts the HTML elements ID,and returns the HTML elements matching that Id.
example:

   document.getElementById('#navBar');
Enter fullscreen mode Exit fullscreen mode

You need to pass the ID of the elements as an arguments, if no element matches the Id then it returns null.

Query Selector
Query selector allows you to use CSS selector to select HTML elements. It is the new way in JavaScript to select elements. There are two types of query selector;

      querySelector();
      querySelectorAll();
Enter fullscreen mode Exit fullscreen mode

query selector is a DOM method. It's accepts the CSS selectors string and only returns the first HTML elements, matching the query,
example;

    document.querySelector('#footer span');
Enter fullscreen mode Exit fullscreen mode

You need to pass the CSS. Selector strings as an argument,If no elements matches the Selector string, then it returns null.

while
querySelectorall is a DOM method that accepts the CSS selector string, and return all of the HTML elements, matching the query.
example;

    document.querySelectorAll('#footer span');
Enter fullscreen mode Exit fullscreen mode

we need to pass the CSS selector string as an argument, If no element that matches, then it returns an empty array

💖 💪 🙅 🚩
izzycious
Ishaq Nasir

Posted on June 27, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

DOCUMENT OBJECT MODEL(DOM)
javascript DOCUMENT OBJECT MODEL(DOM)

June 27, 2022