Home > other >  JavaScript DOM why?
JavaScript DOM why?

Time:01-31

I am currently studying Front end dev with Codecademy. I don't understand why bother to use the DOM with JS to change the elements HTML or CSS, why not go into your HTML / CSS and change it directly from there?

CodePudding user response:

I don't understand why bother to use the DOM with JS to change the elements HTML or CSS, why not go into your HTML / CSS and change it directly from there?

Well that's one approach, but that puts you in 1997, before the DOM was published. That's how websites used to work back then (web 1.0). Static websites without any reactivity or interactivity capabilities. If you want to show images and text, then I think that's fine.

The whole idea behind the DOM is to allow programming languages to interact with the HTML source.

This allows websites to do things automatically. Be reactive. Modern web development libraries such as React use JS to create interactive, fast and reactive websites and all of these is thanks to the existence of the DOM which creates objects from the HTML source code that can be manipulated with programming languages.

I quote from developer.mozilla.org

For example, the document object that represents the document itself, any table objects that implement the HTMLTableElement DOM interface for accessing HTML tables, and so forth, are all objects.

So, lets do something a little bit more interactive.

In the following snippet, as you can see I declare a variable like this const square = document.getElementById('square') what I'm doing there is telling JS that the square variable is the <div> element with id of square.

document is the object that represents the HTML document itself and so, by adding the .getElementById() I can retrieve and manipulate an specific element inside the document object.

So now I can make things change by clicking a button.

const square = document.getElementById('square')

const orange = 'rgb(255, 165, 0)';
const black = 'rgb(0, 0, 0)';

function changeColor(){

  if(square.style.backgroundColor === orange){
    square.style.backgroundColor = black
  }
  else{
    square.style.backgroundColor = orange
  }
  
}
<div id='square' style='width:100px;height:100px;background:#FFA500'></div>
<br>
<button onClick=changeColor()>Change Color</button>

If you want to read more about it, I suggest this link.

Note: using onClick in plain JS is not a good practice, but I'm using it to make the code easier to understand.

CodePudding user response:

Because the page is repesented by DOM. You can set IDL attributes which are not visible in HTML code, the tags are represented by Element objects having bunch of methods not visible in HTML code etc. By editing innerHTML directly (which is relatively slow operation compared to DOM manipulation), you drop the subtree and recreate it with default values, meaning any object settings (like myButton.onclick = handler) is discarded.

  •  Tags:  
  • Related