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

Reading element attributes in HTML in JavaScript

autoload
Release: 2021-04-15 13:57:41
Original
1809 people have browsed it

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>
Copy after login

Read the span tag attribute data in the form:

 <script>
        const sp=document.querySelector("span");
        console.log(sp);
        console.log(sp.id);   
 </script>
Copy after login

    The id can be obtained normally

<script>
        const sp=document.querySelector("span");
        console.log(sp.data-email);
</script>
Copy after login

    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>
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template