What are the differences between properties and attributes in HTML?

6

When attempting to use this code:

  $(document).ready(function(){
    $("#selectAllBoxes").on("click", function(){
       if(this.checked){
           $('.checkBoxes').each(function(){
               $(this).attr("checked", true);
           });
       } else {
           $('.checkBoxes').each(function(){
               $(this).attr("checked", false); 
           });
       }
}

I noticed that it is no longer possible to access jQuery in the "checked" with the attr method, only with prop. After some research I found that HTML properties are elements that we can define as Booleans while attributes can be added to HTML and are not Booleans, but I found this explanation quite generalized. I would like to know what properties and attributes are and what their differences are.

    
asked by anonymous 27.05.2017 / 05:58

1 answer

6

To understand the difference, you need to take into account that HTML and JavaScript are different languages.

So:

  • HTML has elements with attributes
  • JavaScript has objects with properties

The DOM is the interception between JavaScript and HTML, something that there is for example in Node.js. So the objects of the DOM that JavaScript has access to have properties that are the representation of HTML attributes.

Objects that do not have the property of a given JavaScript-defined attribute use the value of the attribute.

Examples:

var a = document.getElementById('a');
var b = document.getElementById('b');
var c = document.getElementById('c');

console.log(a.checked, a.disabled); // true false
console.log(b.checked, b.disabled); // false true

c.setAttribute('disabled', true);
c.checked = true;
console.log(c.checked, c.disabled); // true true
<input checked="checked" type="checkbox" id="a"/>
<input disabled type="checkbox" id="b"/>
<input type="checkbox" id="c"/>

The example a and b behave as expected, JavaScript reads the properties by importing the value of the attributes of the HTML element.

The example c has nothing defined in HTML but we assign value to checked and disabled by changing the object's property, resp. HTML attribute.

Another example:

var c = document.getElementById('c');

c.checked = false;

console.log(c.checked, c.getAttribute('checked')); // false true
<input checked="true" type="checkbox" id="c" />

In this example above the difference becomes even clearer, .checked (property of the object) changes the value only in JavaScript and not HTML where the attribute remains with the initial value.

    
27.05.2017 / 08:48