[JavaScript] DOM manipulation elements


The DOM operation of JavaScript can change the content, structure and style of the web page. We can use the DOM operation element to change the content, attributes, etc. in the element.

  • Elements: All tags in the page are elements, which are elementrepresented

operating elements

change element content

There are two ways to change the content of an element

1.element.innerText
2.element.innerHTML
  1. Changes the content from the start position to the end position, but it removes the html tags, as well as spaces and newlines.
  2. Change the entire content from the start position to the end position, including HTML tags, while preserving spaces and newlines
<body>
    <div></div>
    <p>
        我是文字
        <span>123</span>
    </p>
    <script>
        // 区别 
        // 1. innerText 不识别html标签,去除空格和换行
        var div = document.querySelector('div');
        div.innerText = '<strong>今天是:</strong> 2019';
        // 2. innerHTML 识别html标签 保留空格和换行的
        div.innerHTML = '<strong>今天是:</strong> 2019';
        // 这两个属性是可读写的  可以获取元素里面的内容
        var p = document.querySelector('p');
        console.log(p.innerText);
        console.log(p.innerHTML);
    </script>
</body>

insert image description here

change element attributes

element.属性

For example, modify the value of inputthe label attributevalue

input.value = "改变的值";

change style properties

We can modify the size, color, position and other styles of elements through JS.
inline style

element.style
如div.style.width = '100px';

class name style

//预先写好类,修改类名
element.className

Notice:

The styles in JS adopt camel case naming method, such as fontSize, backgroundColor

JS modifies the style operation to generate an inline style, and the CSS weight is relatively high

If there are many style modifications, you can change the element style by manipulating the class name

class Because it is a reserved word, use className to operate the element class name attribute

className will directly change the class name of the element, and will overwrite the original class name

<style>
  .first {
     
     
    width: 100px;
    height: 100px;
    background-color: skyblue;
  }
  .change {
     
     
    height: 200px;
    background-color: pink;
  }
</style>
<body>
  <div class="first"></div>
  <script>
    var div = document.querySelector('div')
    div.onclick = function() {
     
     
      // this.className = 'change'; //覆盖之前的类

      // 两个类一起
      this.className = 'first change'; //此时有层叠性
    }
  </script>
</body>

Exclusive thought

If there are the same group of elements, we want a certain element to achieve a certain style, and we need to use the exclusive thinking algorithm of the cycle:

  1. All elements clear styles (kill others)
  2. Style the current element (leave me alone)
  3. Note that the order cannot be reversed, first kill others, then set yourself
<body>
    <button>按钮</button>
    <button>按钮</button>
    <button>按钮</button>
    <button>按钮</button>
    <button>按钮</button>
    <button>按钮</button>
    <script>
        var btns = document.getElementsByTagName('button');
        for (var i = 0; i < btns.length; i++) {
     
     
            btns[i].onmouseover = function() {
     
       
                // 把所有按钮颜色去掉
                for (var i = 0; i < btns.length; i++) {
     
     
                    btns[i].style.backgroundColor = ''; 
                }
                //只能用this不能用btns[i] 
                this.style.backgroundColor = 'pink';
                console.log(i);  //6
            }
        }
    </script>
</body>

It can only be used in the code this: when it comes to jsasynchronous issues, it will not be executed immediately after the event is registered, but will be executed after it is activated, so the first layer of for loop is only to register the event, and the ivalue after the loop ends is 6, and it will be executed at this time Activate event, output 6.

custom attributes

get attribute value

element.属性; //获取内置属性值(元素本身自带的属性)
element.getAttribute('属性');  //获取自定义的属性

set attribute value

element.属性 = '值'; //设置内置属性值
element.setAttribute('属性','值'); //主要设置自定义的属性

remove attribute

element.removeAttribute('属性');

the case

<body>
    <div class="demo" index = "1"></div>
    <script>
        var div = document.querySelector('div');
        // 1. 获取元素的属性值
        // (1) element.属性
        console.log(div.className);
        // (2) element.getAttribute('属性')
        console.log(div.getAttribute('class'));
        console.log(div.getAttribute('index'));
        // 2. 设置元素属性值
        // (1) element.属性= '值'
        div.id = 'test';
        div.className = 'navs';
        // (2) element.setAttribute('属性', '值');  主要针对于自定义属性
        div.setAttribute('index', 2);
        div.setAttribute('class', 'footer');
        // 3. 移除属性 removeAttribute(属性)    
        div.removeAttribute('index');
    </script>
</body>

Tab bar switching case

Key point:
Because the problem mentioned above that only this can be used, and there is only one event object, here is the method of taking the subscript of the li element and then traversing the items.

<!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>Document</title>
    <style>
        * {
     
     
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        .tab {
     
     
            width: 400px;
            height: 200px;
            margin: 100px auto;
        }

        .tab_list {
     
     
            height: 40px;
            background-color: #ccc;
        }

        .tab_list li{
     
     
            list-style: none;
            float: left;
            width: 100px;
            height: 40px;
            line-height: 40px;
            text-align: center;
            cursor: pointer;
        }

        .tab_list .current {
     
     
            background-color: red;
            color: #fff;
        }

        .tab_con .item{
     
     
            height: 100px;
            background-color: skyblue;
            display: none;
        }
    </style>
</head>
<body>
    <div class="tab">
        <div class="tab_list">
            <ul>
                <li class="current">1</li>
                <li>2</li>
                <li>3</li>
                <li>4</li>
            </ul>
        </div>
        <div class="tab_con">
            <div class="item" style="display: block;">1</div>
            <div class="item">2</div>
            <div class="item">3</div>
            <div class="item">4</div>
        </div>
    </div>
    <script>
        var lis = document.querySelector('.tab_list').querySelectorAll('li');
        var items = document.querySelector('.tab_con').querySelectorAll('.item');
        for (var i = 0; i < lis.length; i++) {
     
     
            // 给li设置索引号
            lis[i].setAttribute('index',i);
            lis[i].onmouseover = function() {
     
     
                for(var i = 0; i < lis.length; i++) {
     
     
                    lis[i].className = '';
                }
                this.className = 'current';

                // 获得li的索引
                var index = this.getAttribute('index');
                console.log(index);
                for(var i = 0; i < items.length; i++) {
     
     
                    items[i].style.display = 'none';
                }
                items[index].style.display = 'block';
            }
        }
    </script>
</body>
</html>

insert image description here

H5 custom attribute

Custom attribute purpose: to save and save data, some data can be saved to the page instead of to the database.

Disadvantages: Custom attributes can easily cause ambiguity, and it is not easy to judge whether it is a built-in attribute or a custom one.

So H5 has regulations to make it easier to judge custom attributes.
H5 Set custom attributes
H5 stipulates that data-the beginning is used as the attribute name and assigned

<div data-index = "值"></>
div.setAttribute('data-index',值);

H5 get custom attribute method

  1. element.dataset.index
  2. element.dataset['index']

The advantage of using element.getAttribute('data-index')custom attribute acquisition is compatibility issues, browsers are compatible, and the method of h5 acquisition is only supported by IE11.

<body>
    <div getTime="20" data-index="2" data-list-name="andy"></div>
    <script>
        var div = document.querySelector('div');
        console.log(div.getAttribute('getTime'));
        div.setAttribute('data-time', 20);
        console.log(div.getAttribute('data-index'));
        console.log(div.getAttribute('data-list-name'));
        // h5新增的获取自定义属性的方法 它只能获取data-开头的
        // dataset 是一个集合里面存放了所有以data开头的自定义属性
        console.log(div.dataset);
        console.log(div.dataset.index);
        console.log(div.dataset['index']);
        // 如果自定义属性里面有多个-链接的单词,我们获取的时候采取 驼峰命名法
        console.log(div.dataset.listName);
        console.log(div.dataset['listName']);
    </script>
</body>

Guess you like

Origin blog.csdn.net/btufdycxyffd/article/details/127326426