Home >Web Front-end >JS Tutorial >JavaScript sets methods to get and set attributes_javascript tips
getAttribute
This method is used to obtain the attributes of the element. The calling method is as follows:
Different from some methods introduced before, the getAttribute method does not belong to the document object, so it cannot be called through the document object. It can only be called through element node objects.
This method only accepts one parameter, you specify the name of the attribute to be queried. If the specified property is not set, the result will be a null object.
setAttribute
The opposite of the above is setAttribute, which is used to set the attributes of element nodes. The calling method is as follows:
This method only accepts one parameter, which is the attribute you want to set.
Extended reading
After modifying the document through setAttribute, when you view the source code of the document through the browser's view source option, you will still see the value before the change. In other words, setAttribute makes Modifications will not be reflected in the source code of the document itself. This phenomenon of "inconsistency between appearance and inside" comes from the working mode of the DOM: the static content of the document is loaded first, and then dynamically refreshed. The dynamic refresh does not affect the static content of the document. This is the true power of the DOM: refreshing page content without refreshing the page in the browser.
The above two methods are new APIs in DOM Level 1. Before they appear, they can be implemented through another method, for example as follows
Get attributes:
The above is equivalent to
Set properties:
It is equivalent to
If you want to be lazy and less keyboard typing, then the above method is recommended, but the best practice is to respect the DOM standard, that is, use setAttribute and getAttribute.
The above is the entire content of this article. Friends who need it can learn it. I hope you all like it.