当前位置:网站首页>JS attribute operation and node operation

JS attribute operation and node operation

2022-06-12 12:20:00 Yolo. H

API( Application programming interface )

Predefined functions

Web API

Browser provides a set of operations browser functions and page elements API(BOM and DOM)

DOM( Document object model )

1. What is? DOM

W3C Recommended extensible markup language (HTML or XML) Standard programming interface , adopt DOM You can change the content of the web page 、 Structure and pattern

2. Get elements

var timer = document.getElementById('time');
//console.dir  Print the element object we return   Better view the properties and methods inside 
console.dir(timer);  

// Get common elements 
//1.  according to ID obtain 
var ol = document.getElementById('ol');  // Elements 
//2.  Get the element from the tag name 
var lis = document.getElementsByTagName('li');  // Element set 

//H5 New ways to get elements 
//1. Get a collection of certain elements according to the class name 
var boxs = document.getElementsByClassName('box');  // Element set 
//2. Returns the first element object of the specified selector 
var nav = document.querySelector('#nav');   // Elements 
//3. Returns a collection of all element objects of the specified selector 
var allBox = document.querySelectorAll('.box');  // Element set 

// Get special elements 
// 1. obtain body  Elements 
var bodyEle = document.body;
// 2. obtain html  Elements 
var htmlEle = document.documentElement;

3. The basis of the event

//  who   How to trigger   What do you do after you leave 
//  Perform event steps   Event source   Event type   Event handler  
// 1.  Get the event source 
var div = document.querySelector('div');
// 2. The binding event   Registration events 
// div.onclick 
// 3. Add event handler  
div.onclick = function() {
    
    console.log(' I was chosen ');
}

4. Operational elements

Common element attribute modification

Common element attributes :innerHTML、innerText、src、href、id、src、href、alt、title

// Element object . Property name  =  value 
img.src = 'images/zxy.jpg';
img.title = ' Zhang Xueyou, Smecta ';
innerHTML and innerText
var div = document.querySelector('div');
// innerText  and  innerHTML The difference between  
// 1. innerText  Don't recognize html label   Nonstandard   Remove spaces and line breaks 
// 2. innerHTML  distinguish html label  W3C standard   Keep spaces and line breaks 
div.innerText = '<strong> It's today :</strong> 2019';
div.innerHTML = '<strong> It's today :</strong> 2019';
//  These two properties are readable and writable   You can get the content of the element 
var p = document.querySelector('p');
console.log(p.innerText);
console.log(p.innerHTML);
Form attribute settings and this Use

Can pass DOM Change the following form properties :type、value、checked、selected、disabled
The value of the form is through value To change , instead of innerHTML

var btn = document.querySelector('button');
var input = document.querySelector('input');
btn.onclick = function() {
    
    //  The values in the form   The text is written through  value  To modify 
    input.value = " Input ";
    //  If you want a form to be disabled   No more clicks  disabled  We want this button  button Ban 
    btn.disabled = true;
    // Or use this 
    // this  It points to the caller of the event function  btn
    this.disabled = true;
}
Style property operation
operation style attribute
// Element object .style. Style attribute  =  value 
//JS The style naming of is hump naming method 
// What's produced is the in line style 
this.style.backgroundColor = 'purple';
operation className attribute
// Element object .className =  value 
// yes className
// Directly modify the class name , Overwrite the original class 
this.className = 'first change';
Custom properties
<div id="demo" index="1" class="nav"></div>
<script> var div = document.querySelector('div'); // 1.  Gets the attribute value of the element  // (1) element. attribute   // Get built-in property values  console.log(div.id); //(2) element.getAttribute(' attribute ')  // Get the attributes added by our programmers, which we call custom attributes  index console.log(div.getAttribute('id')); console.log(div.getAttribute('index')); //2. Setting property values  // (1) element. attribute = ' value ' // Set built-in property values  div.id = 'test'; div.className = 'navs'; // (2) element.setAttribute(' attribute ', ' value ');  // It is mainly aimed at custom attributes  div.setAttribute('index', 2); // class  special   It says class  No className div.setAttribute('class', 'footer'); // 3  Remove properties  removeAttribute( attribute )  div.removeAttribute('index'); </script>
H5 Custom properties
  1. H5 Specify custom attributes data- Start with the property name and assign a value .
<div data-index=“1”></div>
  1. obtain H5 Custom properties
//1. Compatibility gains  element.getAttribute(‘data-index’);
//2. H5 newly added  element.dataset.index 
//  or  element.dataset[‘index’] 
// ie 11 Just started to support 
<div getTime="20" data-index="2" data-list-name="andy"></div>
<script>
    var div = document.querySelector('div');
    
    console.log(div.getAttribute('data-index'));
    console.log(div.getAttribute('data-list-name'));
    
    // h5 New method to get custom attributes   It can only get data- At the beginning 
    // dataset  It's a collection that holds all the information in data Custom properties at the beginning 
    console.log(div.dataset);
    console.log(div.dataset.index);
    console.log(div.dataset['index']);
    
    //  If there are multiple custom attributes - Linked words , We take... When we get it   Hump nomenclature 
    console.log(div.dataset.listName);
    console.log(div.dataset['listName']);
</script>

5. Exclusive thoughts

If you have the same set of elements , We want an element to implement a certain style , Need to use the exclusive thought algorithm of the loop :

  1. All elements clear the style ( Kill the others )
  2. Style the current element ( Leave me alone )
  3. Note that the order cannot be reversed , First kill the others , Set yourself up
// 1.  Get all button elements 
var btns = document.getElementsByTagName('button');
// btns The result is a pseudo array   Every element in it  btns[i]
for (var i = 0; i < btns.length; i++) {
    
	// Event triggers event 
    btns[i].onclick = function() {
    
        // (1)  Let's remove all the button background colors first   Get rid of everyone 
        for (var i = 0; i < btns.length; i++) {
    
            btns[i].style.backgroundColor = '';
        }
        // (2)  Then let the current element background color be pink  Leave me alone 
        //this  It points to the caller of the event function  btns[i]
        // You need to use this, instead of btns[i]
        // Because this is just an event registration function 
        // It describes the event executed after the event is triggered under specific conditions 
        // And when the event is triggered , The cycle is over , At this time i Always the same 
        this.style.backgroundColor = 'pink';
    }
}

6. Node operation

Using parent-child sibling node relationship to obtain elements , Strong logic , But the compatibility is slightly poor
label 、 attribute 、 Text 、 Notes, etc. It's all nodes Node

Node Foundation

Nodes have at least nodeType( Node type )nodeName( The name of the node ) and nodeValue( Node values ) These three
Basic attributes .
Element nodes nodeType by 1
Attribute node nodeType by 2
Text node nodeType by 3( The text node contains text 、 Space 、 Line break, etc )
Generally, nodes are divided into different hierarchical relationships , Common is Father, son and brother Hierarchy

Get parent node
<div class="box">
   <span class="erweima">×</span>
</div>

<script> //node.parentNode  //parentNode  Property returns the parent node of a node , Notice the nearest parent node  // If the specified node has no parent node, return  nul // 1.  Parent node  parentNode var erweima = document.querySelector('.erweima'); console.log(erweima.parentNode); </script>
Get child nodes
  • parentNode.childNodes( standard )
    but parentNode.childNodes Returns a collection of children of a specified node , The set is an instant update set , And Return value It contains All child nodes , Include Element nodes , Text node , If you only want to get the element nodes inside , It needs to be dealt with specially , according to nodeType == 1 Judge
  • parentNode.children( Nonstandard )
    parentNode.children It's a read-only attribute , return All child element nodes . It only returns Child element node , The remaining nodes do not return , Supported by various browsers , Focus on this
<ul>
    <li> I am a li</li>
    <li> I am a li</li>
    <li> I am a li</li>
    <li> I am a li</li>
</ul>
<script> // DOM  Methods provided (API) obtain  var ul = document.querySelector('ul'); var lis = ul.querySelectorAll('li'); // 1.  Child node  childNodes  All child nodes   contain   Element nodes   Text nodes and so on  console.log(ul.childNodes); console.log(ul.childNodes[0].nodeType); console.log(ul.childNodes[1].nodeType); // 2. children  Get all child element nodes   It is also commonly used in our actual development  console.log(ul.children); </script>
For the first 1 Child node
  • parentNode.firstChild
    Return to the first child node , Return if not found null. It also contains all the nodes
  • parentNode.firstElementChild
    Returns the first child node , Return if not found null.
    But there are compatibility problems ,IE9 The above supports
  • parentNode.chilren[0]
Get last 1 Child node
  • parentNode.lastChild
    Returns the last child node , Return if not found null. It also contains all the nodes
  • parentNode.lastElementChild
    Returns the last child element node , Return if not found null.
    But there are compatibility problems ,IE9 The above supports
  • parentNode.chilren[parentNode.chilren.length - 1]
<ol>
    <li> I am a li1</li>
    <li> I am a li2</li>
    <li> I am a li3</li>
    <li> I am a li4</li>
    <li> I am a li5</li>
</ol>
<script> var ol = document.querySelector('ol'); // 1. firstChild  First child node   Whether it's a text node or an element node  console.log(ol.firstChild); console.log(ol.lastChild); // 2. firstElementChild  Returns the first child node  ie9 To support  console.log(ol.firstElementChild); console.log(ol.lastElementChild); // 3.  The actual development of writing   There is no compatibility problem and the first child element is returned  console.log(ol.children[0]); console.log(ol.children[ol.children.length - 1]); </script>
Get the last sibling node
  • node.previousSibling
    Returns the previous sibling element node of the current element , Return if not found null.
    It also contains all the nodes .
  • node.previousElementSibling
    Returns the previous sibling element node of the current element , Return if not found null.
    But there are compatibility problems ,IE9 The above supports
Gets the next sibling node
  • node.nextSibling
    Returns the next sibling node of the current element , Return if not found null.
    It also contains all the nodes .
  • node.nextElementSibling
    Returns the next sibling element node of the current element , Return if not found null.
    But there are compatibility problems ,IE9 The above supports
<div> I am a div</div>
<span> I am a span</span>
<script> var div = document.querySelector('div'); // 1.nextSibling  Next sibling node   Contains element nodes or   Text nodes and so on  console.log(div.nextSibling); console.log(div.previousSibling); // 2. nextElementSibling  Get the next sibling node  console.log(div.nextElementSibling); console.log(div.previousElementSibling); </script>
Cancel compatibility
// Compatibility functions 
function getNextElementSibling(element) {
    
	 var el = element;
	 while (el = el.nextSibling) {
    
	 	if (el.nodeType === 1) {
    
	 		return el;
	 	}
	 }
	 return null;
} 
Create nodes

document.createElement()

Add a node
  • node.appendChild(child)
    Adds a node to the of the specified parent node At the end of the list of child nodes
  • node.insertBefore(child, Specify elements )
    Add a node to the specified of the parent node Before child node
<ul>
    <li>123</li>
</ul>
<script> // 1.  Create a node element node  var li = document.createElement('li'); // 2.  Add a node  node.appendChild(child)  //node  Parent  child  It's a child   Append element after  var ul = document.querySelector('ul'); ul.appendChild(li); // 3.  Add a node  node.insertBefore(child,  Specify elements ); var lili = document.createElement('li'); ul.insertBefore(lili, ul.children[0]); // 4.  We want to add a new element to the page  : 1.  Create elements  2.  Additive elements  </script>

7. Classic case list

Select all and deselect all cases
// 1.  Select all and deselect all :  Let all the check boxes below checked attribute ( Selected state )  Follow   Just press the select all button 
//  Get elements 
// Get select all button 
var j_cbAll = document.getElementById('j_cbAll'); 
// Get sub button 
var j_tbs = document.getElementById('j_tb').getElementsByTagName('input'); 

//  Select all button registration event 
j_cbAll.onclick = function() {
    
        // this.checked  The selection status of the current check box 
        console.log(this.checked);
        for (var i = 0; i < j_tbs.length; i++) {
    
            j_tbs[i].checked = this.checked;
        }
 }
 //  Register click events for all sub checkboxes 
for (var i = 0; i < j_tbs.length; i++) {
    
    j_tbs[i].onclick = function() {
    
        // flag  Controls whether the select all button is selected 
        var flag = true;
        //  Cycle the checker every time you click the check box below 4 Whether all the small buttons are selected 
        for (var i = 0; i < j_tbs.length; i++) {
    
            if (!j_tbs[i].checked) {
    
                flag = false;
                break; 
            }
        }
        //  Set the status of the select all button 
        j_cbAll.checked = flag;
    }
}
tab bar
//  Get elements 
var tab_list = document.querySelector('.tab_list'); 
var lis = tab_list.querySelectorAll('li');  // List header 
var items = document.querySelectorAll('.item');  // Content 
// for loop , Bind click events to tabs 
for (var i = 0; i < lis.length; i++) {
    
    //  Start giving 5 Small li  Set the index number  
    lis[i].setAttribute('index', i);
    lis[i].onclick = function() {
    
        // 1.  The modules tab on the , The current background color will be red , The rest remains the same ( Exclusive thoughts )
        //  Get rid of everyone   The rest li eliminate  class  This class 
        for (var i = 0; i < lis.length; i++) {
    
            lis[i].className = '';
        }
        //  Leave me alone  
        this.className = 'current';
        // 2.  The following display content module 
        var index = this.getAttribute('index');
        console.log(index);
        //  Get rid of everyone   Let the rest item  these div  hide 
        for (var i = 0; i < items.length; i++) {
    
            items[i].style.display = 'none';
        }
        //  Leave me alone   Let the corresponding item  Show it 
        items[index].style.display = 'block';
    }
}
The drop-down menu
// 1.  Get elements 
var nav = document.querySelector('.nav');
var lis = nav.children; //  obtain 4 Small li
// 2. Loop register events 
for (var i = 0; i < lis.length; i++) {
    
   lis[i].onmouseover = function() {
    
       this.children[1].style.display = 'block';
   }
   lis[i].onmouseout = function() {
    
       this.children[1].style.display = 'none';
   }
}
Message board
<body>
    <textarea name="" id=""></textarea>
    <button> Release </button>
    <ul>

    </ul>
    <script> // 1.  Get elements  var btn = document.querySelector('button'); var text = document.querySelector('textarea'); var ul = document.querySelector('ul'); // 2.  Registration events  btn.onclick = function() {
       if (text.value == '') {
       alert(' You have not entered anything '); return false; } else {
       // console.log(text.value); // (1)  Create elements  var li = document.createElement('li'); //  To have a first li  Can be assigned  li.innerHTML = text.value; // (2)  Additive elements  // ul.appendChild(li); ul.insertBefore(li, ul.children[0]); } } </script>
</body>
原网站

版权声明
本文为[Yolo. H]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/03/202203010521234997.html