Home >Web Front-end >JS Tutorial >Reading element attributes in HTML in JavaScript
In JavaScrip
t, after the element is obtained, the values of some attributes can be obtained normally, but some attributes After accessing the value, the answer obtained is undefined
. This article will take you to find out.
Contents in the form:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title></title> </head> <body> <span id="user" data-email="a@qq.com" >jojo的奇妙</span> </body> </html>
Read the span tag attribute data in the form:
<script> const sp=document.querySelector("span"); console.log(sp); console.log(sp.id); </script>
The id can be obtained normally
<script> const sp=document.querySelector("span"); console.log(sp.data-email); </script>
Error: Uncaught ReferenceError: email is not defined, the value of email cannot be obtained.
PS: id
is the default built-in standard attribute
, which can be accessed directly, email
is Non-built-in properties
,undefined
.
<script> const sp=document.querySelector("span"); console.log(p.dataset.email); //对于自定义的数据属性"data-",使用dataset对象来操作 </script>
Recommended: "2021 js interview questions and answers (large summary)"
The above is the detailed content of Reading element attributes in HTML in JavaScript. For more information, please follow other related articles on the PHP Chinese website!