In our previous tutorial we learned about python system command. In this tutorial we will be discussing about Python getattr() function. Show Python getattr() functionPython getattr() function is used to get the value of an object’s attribute and if no attribute of that object is found, default value is returned. Basically, returning the default value is the main reason why you may need to use Python getattr() function. So, before starting the tutorial, lets see the basic syntax of Python’s getattr() function. getattr(object_name, attribute_name[, default_value])Python getattr() exampleIn this section, we will learn how to access attribute values of an object using getattr() function. Suppose, we are writing a class named Student. The basic attributes of Student class are student_id and student_name. Now we will create an object of the class Student and access it’s attribute. class Student: student_id="" student_name="" # initial constructor to set the values def __init__(self): self.student_id = "101" self.student_name = "Adam Lam" student = Student() # get attribute values by using getattr() function print('\ngetattr : name of the student is =', getattr(student, "student_name")) # but you could access this like this print('traditional: name of the student is =', student.student_name)So, the output will be like this Python getattr() default valueIn this section, we will use the python getattr() default value option. If you want to access any attribute that doesn’t belong to the object, then you can use the getattr() default value option. For example, if the student_cgpa attribute is not present for the student, then will show a default value. In the following example we will see example of default value. We will also learn what happens if the attribute is not present and we are not using the default value option. class Student: student_id="" student_name="" # initial constructor to set the values def __init__(self): self.student_id = "101" self.student_name = "Adam Lam" student = Student() # using default value option print('Using default value : Cgpa of the student is =', getattr(student, "student_cgpa", 3.00)) # without using default value try: print('Without default value : Cgpa of the student is =', getattr(student, "student_cgpa")) except AttributeError: print("Attribute is not found :(")So, after running the code you will get output like this Using default value : Cgpa of the student is = 3.0 Attribute is not found :(Notice that AttributeError is raised when the default value is not provided while calling getattr() function. Reason for using Python getattr() functionThe main reason to use python getattr() is that we can get the value by using the name of the attribute as String. So you can manually input the attribute name in your program from console. Again, if an attribute is not found you can set some default value, which enables us to complete some of our incomplete data. Also if your Student class is work in progress, then we can use getattr() function to complete other code. Once Student class has this attribute, it will automatically pick it up and not use the default value. So, that’s all about python getattr() function. If you have any query about this, please use the comment box below. Reference: Official Documentation The getAttribute() method of the Element interface returns the value of a specified attribute on the element. If the given attribute does not exist, the value returned will either be null or "" (the empty string); see Non-existing attributes for details. getAttribute(attributeName)
A string containing the value of attributeName. <div id="div1">Hi Champ!</div> const div1 = document.getElementById('div1'); const exampleAttr= div1.getAttribute('id'); const align = div1.getAttribute('align') When called on an HTML element in a DOM flagged as an HTML document, getAttribute() lower-cases its argument before proceeding. All modern web browsers return null when the specified attribute does not exist on the specified element. For security reasons, CSP nonces from non-script sources, such as CSS selectors, and .getAttribute("nonce") calls are hidden. let nonce = script.getAttribute('nonce'); Instead of retrieving the nonce from the content attribute, use the nonce property: let nonce = script.nonce;
BCD tables only load in the browser When the browser loads the page, it “reads” (another word: “parses”) the HTML and generates DOM objects from it. For element nodes, most standard HTML attributes automatically become properties of DOM objects. For instance, if the tag is <body id="page">, then the DOM object has body.id="page". But the attribute-property mapping is not one-to-one! In this chapter we’ll pay attention to separate these two notions, to see how to work with them, when they are the same, and when they are different. DOM propertiesWe’ve already seen built-in DOM properties. There are a lot. But technically no one limits us, and if there aren’t enough, we can add our own. DOM nodes are regular JavaScript objects. We can alter them. For instance, let’s create a new property in document.body:
document.body.myData = { name: 'Caesar', title: 'Imperator' }; alert(document.body.myData.title); // Imperator We can add a method as well:
document.body.sayTagName = function() { alert(this.tagName); }; document.body.sayTagName(); // BODY (the value of "this" in the method is document.body) We can also modify built-in prototypes like Element.prototype and add new methods to all elements:
Element.prototype.sayHi = function() { alert(`Hello, I'm ${this.tagName}`); }; document.documentElement.sayHi(); // Hello, I'm HTML document.body.sayHi(); // Hello, I'm BODY So, DOM properties and methods behave just like those of regular JavaScript objects:
HTML attributesIn HTML, tags may have attributes. When the browser parses the HTML to create DOM objects for tags, it recognizes standard attributes and creates DOM properties from them. So when an element has id or another standard attribute, the corresponding property gets created. But that doesn’t happen if the attribute is non-standard. For instance:
<body id="test" something="non-standard"> <script> alert(document.body.id); // test // non-standard attribute does not yield a property alert(document.body.something); // undefined </script> </body> Please note that a standard attribute for one element can be unknown for another one. For instance, "type" is standard for <input> (HTMLInputElement), but not for <body> (HTMLBodyElement). Standard attributes are described in the specification for the corresponding element class. Here we can see it:
<body id="body" type="..."> <input id="input" type="text"> <script> alert(input.type); // text alert(body.type); // undefined: DOM property not created, because it's non-standard </script> </body> So, if an attribute is non-standard, there won’t be a DOM-property for it. Is there a way to access such attributes? Sure. All attributes are accessible by using the following methods:
These methods operate exactly with what’s written in HTML. Also one can read all attributes using elem.attributes: a collection of objects that belong to a built-in Attr class, with name and value properties. Here’s a demo of reading a non-standard property:
<body something="non-standard"> <script> alert(document.body.getAttribute('something')); // non-standard </script> </body> HTML attributes have the following features:
Here’s an extended demo of working with attributes:
<body> <div id="elem" about="Elephant"></div> <script> alert( elem.getAttribute('About') ); // (1) 'Elephant', reading elem.setAttribute('Test', 123); // (2), writing alert( elem.outerHTML ); // (3), see if the attribute is in HTML (yes) for (let attr of elem.attributes) { // (4) list all alert( `${attr.name} = ${attr.value}` ); } </script> </body> Please note:
Property-attribute synchronizationWhen a standard attribute changes, the corresponding property is auto-updated, and (with some exceptions) vice versa. In the example below id is modified as an attribute, and we can see the property changed too. And then the same backwards:
<input> <script> let input = document.querySelector('input'); // attribute => property input.setAttribute('id', 'id'); alert(input.id); // id (updated) // property => attribute input.id = 'newId'; alert(input.getAttribute('id')); // newId (updated) </script> But there are exclusions, for instance input.value synchronizes only from attribute → property, but not back:
<input> <script> let input = document.querySelector('input'); // attribute => property input.setAttribute('value', 'text'); alert(input.value); // text // NOT property => attribute input.value = 'newValue'; alert(input.getAttribute('value')); // text (not updated!) </script> In the example above:
That “feature” may actually come in handy, because the user actions may lead to value changes, and then after them, if we want to recover the “original” value from HTML, it’s in the attribute. DOM properties are typedDOM properties are not always strings. For instance, the input.checked property (for checkboxes) is a boolean:
<input id="input" type="checkbox" checked> checkbox <script> alert(input.getAttribute('checked')); // the attribute value is: empty string alert(input.checked); // the property value is: true </script> There are other examples. The style attribute is a string, but the style property is an object:
<div id="div" style="color:red;font-size:120%">Hello</div> <script> // string alert(div.getAttribute('style')); // color:red;font-size:120% // object alert(div.style); // [object CSSStyleDeclaration] alert(div.style.color); // red </script> Most properties are strings though. Quite rarely, even if a DOM property type is a string, it may differ from the attribute. For instance, the href DOM property is always a full URL, even if the attribute contains a relative URL or just a #hash. Here’s an example:
<a id="a" href="#hello">link</a> <script> // attribute alert(a.getAttribute('href')); // #hello // property alert(a.href ); // full URL in the form http://site.com/page#hello </script> If we need the value of href or any other attribute exactly as written in the HTML, we can use getAttribute. Non-standard attributes, datasetWhen writing HTML, we use a lot of standard attributes. But what about non-standard, custom ones? First, let’s see whether they are useful or not? What for? Sometimes non-standard attributes are used to pass custom data from HTML to JavaScript, or to “mark” HTML-elements for JavaScript. Like this:
<!-- mark the div to show "name" here --> <div show-info="name"></div> <!-- and age here --> <div show-info="age"></div> <script> // the code finds an element with the mark and shows what's requested let user = { name: "Pete", age: 25 }; for(let div of document.querySelectorAll('[show-info]')) { // insert the corresponding info into the field let field = div.getAttribute('show-info'); div.innerHTML = user[field]; // first Pete into "name", then 25 into "age" } </script> Also they can be used to style an element. For instance, here for the order state the attribute order-state is used:
<style> /* styles rely on the custom attribute "order-state" */ .order[order-state="new"] { color: green; } .order[order-state="pending"] { color: blue; } .order[order-state="canceled"] { color: red; } </style> <div class="order" order-state="new"> A new order. </div> <div class="order" order-state="pending"> A pending order. </div> <div class="order" order-state="canceled"> A canceled order. </div> Why would using an attribute be preferable to having classes like .order-state-new, .order-state-pending, .order-state-canceled? Because an attribute is more convenient to manage. The state can be changed as easy as:
// a bit simpler than removing old/adding a new class div.setAttribute('order-state', 'canceled'); But there may be a possible problem with custom attributes. What if we use a non-standard attribute for our purposes and later the standard introduces it and makes it do something? The HTML language is alive, it grows, and more attributes appear to suit the needs of developers. There may be unexpected effects in such case. To avoid conflicts, there exist data-* attributes. All attributes starting with “data-” are reserved for programmers’ use. They are available in the dataset property. For instance, if an elem has an attribute named "data-about", it’s available as elem.dataset.about. Like this:
<body data-about="Elephants"> <script> alert(document.body.dataset.about); // Elephants </script> Multiword attributes like data-order-state become camel-cased: dataset.orderState. Here’s a rewritten “order state” example:
<style> .order[data-order-state="new"] { color: green; } .order[data-order-state="pending"] { color: blue; } .order[data-order-state="canceled"] { color: red; } </style> <div id="order" class="order" data-order-state="new"> A new order. </div> <script> // read alert(order.dataset.orderState); // new // modify order.dataset.orderState = "pending"; // (*) </script> Using data-* attributes is a valid, safe way to pass custom data. Please note that we can not only read, but also modify data-attributes. Then CSS updates the view accordingly: in the example above the last line (*) changes the color to blue. Summary
A small comparison:
Methods to work with attributes are:
For most situations using DOM properties is preferable. We should refer to attributes only when DOM properties do not suit us, when we need exactly attributes, for instance:
|