Home  >  Article  >  Web Front-end  >  js tutorial--dom code to get elements

js tutorial--dom code to get elements

php是最好的语言
php是最好的语言Original
2018-08-09 13:20:331296browse

  1. Get elements:

    1. document.getElementsByClassName ('class') Get elements by class name, as array of classes Form exists. getElementsByTagName

    2. document.querySelector('selector') Gets the element through the CSS selector, the 1 that meets the matching conditions element.

    3. document.querySelectorAll('selector') Gets elements through CSS selectors, in an array-like form.

  2. ## Class name operation:

    1. Node.classList. add('class') Add class

    2. Node.classList.remove('class') Remove class

    3. Node.classList.toggle ('class') Switch the class, remove it if it exists, add it if it doesn't

    4. Node.classList.contains('class') Check whether the class exists

  3. Custom attributes:

In HTML5 we can customize attributes, the format is as follows data-* ="", for example: data-info="I am a custom attribute", through Node.dataset['info'] we can get the custom attribute value.

When we set the format as follows, we need to use camel case format to get it correctly: data-my-name="itcast", get Node.dataset['myName']

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .red{
            color: red;
        }
        .green{
            color: green;
        }
        .blue{
            color: blue;
        }
    </style>
</head>
<body>
<ul>
    <li>请选择</li>
    <li class="red">前端</li>
    <li class="green">java</li>
    <li class="blue">javascript</li>
    <li id="c">c++</li>
</ul>
<script>
    /*获取第一个li标签*/
    window.onload=function(){
        /*ElementsByTagName获取的是数组*/
        /*索引:不直观 以后的数据都是从后台动态获取,前台动态生成添加*/
        /*var cli=document.getElementsByTagName("li")[1];
        console.log(cli);*/

        /*query:查询  Selector:选择器   querySelector(传入选择器名称)*/
        /*querySelector:获取单个元素,如果获取的元素不止一个,那么只会返回满足条件的第一个元素*/
        /*参数要求:如果是类选择器,必须添加.  如果是id选择器, 必须添加# ,否则当成标签处理*/
        var javaLi=document.querySelector(".green");
        //var javaLi=document.querySelector("#c");
        console.log(javaLi);

        /*querySelectorAll获取满足条件的所有元素--数组*/
        var allLi=document.querySelectorAll("li")[0];
        console.log(allLi);
    }
</script>
</body>
</html>

Related recommendations:

Native js gets the dom element in the iframe--the parent and child pages get each other's dom

How to get the DOM element in js

The above is the detailed content of js tutorial--dom code to get elements. 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