HI WELCOME TO SIRIS

html attribute vs dom property

Leave a Comment

What is DOM

DOM stands for Document Object Model. When a browser loads a web page, the browser creates a Document Object Model of that page.


For example, for the HTML below,
dom property vs attribute

The browser creates a Document Object Model of that page as shown below
difference between html attribute and property

So in simple terms you can think of the DOM as an application programming interface (API) for HTML, and we can use programming languages like JavaScript, or JavaScript frameworks like Angular to access and manipulate the HTML using their corresponding DOM objects.

In other words DOM contains the HTML elements as objects, their properties, methods and events and it is a standard for accessing, modifying, adding or deleting HTML elements.

In the previous 2 videos we discussed interpolation and property binding in Angular.

Interpolation example
<button disabled='{{isDisabled}}'>Click Me</button>

Property binding example
<button [disabled]='isDisabled'>Click Me</button>

If you notice the above 2 examples, it looks like we are binding to the Button's disabled attribute. This is not true. We are actually binding to the disabled property of the button object. Angular data-binding is all about binding to DOM object properties and not HTML element attributes.

What is the difference between HTML element attribute and DOM property
  1. Attributes are defined by HTML, where as properties are defined by the DOM.
  2. Attributes initialize DOM properties. Once the initialization complete, the attributes job is done.
  3. Property values can change, where as attribute values can't.
Let's prove this point - Property values change, but the attribute values don't with an example.

In the example below, we have set the value attribute of the input element to Tom.
<input id='inputId' type='text' value='Tom'>

At this point, run the web page and in the textbox you will see 'Tom' as the value. 

Launch the browser developer tools.

On the 'Console' tab, use the getattribute() method and value property of the input element to get the attribute and property values. Notice at the moment both have the value 'Tom'
html element property vs attribute

Change the value in the textbox to Mary.

Notice now, when we query for the attribute and property values, the attribute value is still Tom but the property value is Mary. So this proves the point - Property values change, where as attribute values don't.
html attribute vs property

So it is important to keep in mind that, 
  1. HTML attributes and the DOM properties are different things.
  2. Angular binding works with properties and events, and not attributes.
  3. The role of attributes is to initialize element properties and their job is done.

0 comments:

Post a Comment

Note: only a member of this blog may post a comment.