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>
JavaScript And DOM
- JavaScript can add new HTML elements and attributes.
- JavaScript can change all the CSS styles in a page
- JavaScript can add and listen to HTML events like onScroll hover onclick, etc.
- JavaScript can change any HTML elements and attributes of a page.
- JavaScript can remove existing HTML elements and attributes.
Now, how do we add JavaScript to an HTML documents
<script>
console.log('active');
</script>
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');
getElementById is a DOM method which accepts the HTML elements ID,and returns the HTML elements matching that Id.
example:
document.getElementById('#navBar');
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();
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');
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');
we need to pass the CSS selector string as an argument, If no element that matches, then it returns an empty array
Top comments (0)