What are the differences between properties and attributes in HTML?

Asked

Viewed 1,874 times

7

When trying 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 realized that it is no longer possible to access in jQuery the "checked" with the attr method, only with prop. After some researches I found that the properties of HTML are elements that we can define as boolean while the attributes can be added to HTML and are not boolean, but I found this explanation quite widespread. I would like to know what the properties and attributes are and what their differences are.

1 answer

7


To understand the difference it is necessary to take into account that HTML and Javascript are different languages.

Thus:

  • 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 DOM objects that Javascript has access to have properties that are the representation of HTML attributes.

Objects that do not have the property of a given attribute defined Javascript uses the attribute value.

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 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 changing object 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, the .checked (object property) changes the value only in Javascript and not in HTML where the attribute remains with the initial value.

  • 1

    Excellent explanation, thank you very much.

  • 1

    @Velasco of nothing, good question!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.