The difference between attr () and prop () in jquery

Time:2021-11-22

Problem introduction

I received a job yesterday. There was a small demand. I encountered a small problem in the process of writing. Although this problem is not very complicated, it is a more detailed problem. I believe many novice front-end will encounter. Let me first describe the demand I encountered.

Requirements are very simple, the use of a very simple check box. You need to implement the following three logics:

  1. Check “national” and the eastern, southern, Western and northern districts will be selected

  2. If you uncheck “national”, the eastern, southern, Western and northern districts will be deselected

  3. If all four regions are selected, “national” will be checked. If one of the four regions is not checked, “all” will not be checked

When dealing with this requirement, I first thought of the attr () method in jQuery! Attr (“checked”, true) in this way, you can control the check box, but there are two problems when I judge:

  1. When the check box is checked, it returns undefined when using attr (“checked”) to obtain its status

  2. When you have not checked the check box, attr (“checked”, true) or attr (“checked”, false) is valid, but after checking, attr (“checked”, true) or attr (“checked”, false) is invalid

These two questions make me very confused. After consulting the data, I found the reason. Today, let’s talk about the difference between attr () and prop () in jQuery to explain the reasons for the above two problems. In addition, this is also a problem that novice front-end is easy to ignore.

If you want to do well, you must first sharpen your tools. First, talk about the difference between attribute and property

To understand the difference between attr () and prop () in jQuery, we must first understand the difference between attribute and property. When we understand these two attributes, it will be easy to understand the difference between attr () and prop () in jQuery. Attribute and property are very easy to confuse for students who have just entered the front end. Here, I would like to summarize the following four points:

1.The attribute of DOM node is both attribute and property. Modifying attribute or property can change the attribute

2.Attribute and property are user-defined attributes that cannot be accessed to each other

3.Attribute only supports string type, while property can support string, number and Boolean

4.The custom attribute of attribute can be viewed in innerHTML, but the custom attribute of property cannot be viewed in innerHTML

After reading the above summary, I believe there are still many students who can’t understand. So I write some small cases for students to understand the difference between attribute and property.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    < title > difference between attribute and property < / Title >
</head>
<body>
Check box < input type = "checkbox" id = "testcheckbox" / >
</body>
</html>
<script>
    var oCheckbox=document.getElementById("testCheckBox");
//Set attribute
    oCheckbox.setAttribute("value","boxValue");
    console.log(oCheckbox.value);//boxValue
//Set property
    oCheckbox.name="boxName";
    console.log(oCheckbox.getAttribute("name"));//boxName
//Custom attribute
    oCheckbox.setAttribute("myValue","myBoxValue");
    console.log(oCheckbox.myValue);//undefined
//Custom property
    oCheckbox.myName="myBoxName";
    console.log(oCheckbox.getAttribute("myName"));//null
//Set property(number类型)
    oCheckbox.num=1;
    console.log(typeof(oCheckbox.num));//number
//Set property(boolean类型)
    oCheckbox.isPost=true;
    console.log(typeof(oCheckbox.isPost));//boolean
//Attribute support type
    oCheckbox.setAttribute("attrValue",1);
    console.log(typeof(oCheckbox.getAttribute("attrValue")));//string
    oCheckbox.setAttribute("isChecked",true);
    console.log(typeof(oCheckbox.getAttribute("isChecked")));//string
</script>

Here’s a warm reminder. When we set the class attribute and use ocheckbox.class to get it, the control prompt is undefined. In property, it is classname instead of class, which is very similar to document. Getelementsbyclassname(). Careful friends will find that when I set my own property with property, the returned type is string, which is inconsistent with the third point above! Here we will go back to the first point. The built-in attribute is both attribute and property, but the attribute only supports string type. When we set the built-in attribute with property, it will be automatically converted to string type to meet the requirement that the attribute only supports string type, so our built-in attribute can only be string type.

Lift the veil of attr () and prop ()

After finishing attribute and property, we will talk about attrib () and prop () in jQuery. As mentioned earlier, we mentioned two confusing places. Let’s explain the reasons one by one.
1、 When the check box is checked, it returns undefined when using attr (“checked”) to obtain its status

Here, we note that the attribute obtained with attr () must be the attribute you can see on the DOM node. If you can’t see it, it will return undefined. Here we can verify that when you use attr (“checked”, true), you will find that the corresponding DOM node will add a checked = “checked” attribute. When you use attr (“checked”) to obtain its checked attribute, you will return the “checked” string, which verifies this sentence.

The attribute obtained with attr () must be the attribute you can see on the DOM node. If you can’t see it, it will return undefined.

For the attributes defined by the DOM node itself, prop () can’t get them, while attr () can. If the tag comes with it, it can get them. The reason is that when we summarized attribute and property earlier, the attributes of the DOM node mentioned are both attribute and property.

2 、When you have not checked the check box, attr (“checked”, true) or attr (“checked”, false) is valid, but after checking, attr (“checked”, true) or attr (“checked”, false) is invalid

One thing we need to make clear here is that attr (“checked”, true) and attr (“checked”, false) actually set not the checked attribute, but the defaultchecked attribute. Only by checking and unchecking can we change the checked attribute, which is equivalent to executing prop (“checked”, true) or prop (“checked”, false) statements. When we do not modify the checked attribute, the check condition of the check box is controlled by the defaultchecked attribute. After we modify the checked attribute, the check condition of the check box will be taken over by the checked attribute, and the defaultchecked attribute will become invalid unless you refresh the page again.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    National < input id = "allarea" type = "checkbox" / >
</body>
</html>
//Remember to introduce jQuery
<script></script>
<script>
      console.log($("#allArea").get(0).defaultChecked);//false
      console.log($("#allArea").prop("defaultChecked"));//false
      $("#allArea").attr("checked",true);
      console.log($("#allArea").get(0).defaultChecked);//true
    console.log($("#allArea").prop("defaultChecked"));//true
</script>

epilogue

The two problems raised at the beginning of our article have been solved. Here we summarize the usage scenarios of attr () and prop ().

When setting the properties of Boolean types such as disabled, selected and checked, we need to use the prop () method; When other string types have their own attributes, we can use the attr () method; For the custom attributes visible to DOM nodes, we also use the attr () method.