Home  >  Article  >  Web Front-end  >  Reading element attributes in HTML in JavaScript

Reading element attributes in HTML in JavaScript

autoload
autoloadOriginal
2021-04-07 16:47:021699browse

Reading element attributes in HTML in JavaScript

In JavaScript, 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn