WebAPIs基础知识05

Wenn 于 2022-09-11 发布

节点操作

查找节点

<div class='box'>
    <i>标签</i>
    <p>段落</p>
    <h2>标题</h2>
</div>
//查找父节点 sonElement.parentNode
const i = document.querySelector('i');
console.log(i.parentNode);  //输出div标签
sonsole.log(i.parentNode.parentNode);  //输出body标签
//查找子节点 fatherElement.children childNodes
const box = document.querySelector('.box')
console.log(box.childNodes);   //box下的所有子节点,包含换行、空格以及制表符
//NodeList(7) [text, i, text, p, text, h2, text]

console.log(box.children);  //box下的所有子元素节点
//HTMLCollection(3) [i, p, h2]

console.log(box.firstElementChild);  //box下第一个子元素节点
console.log(box.lastElementChild);  //box下最后一个子元素节点
console.log(box.childElementCount);  //3,box下有几个子元素节点
//查找兄弟节点
//nextElementSibling  previousElementSibling
const p = document.querySelector('p');
console.log(p.nextElementSibling); //输出h2标签
console.log(p.previousElementSibling);  //输出i标签

增加节点

//创建元素 document.createElement('tagName');
//追加节点 father.appendChild(); 父元素调用,加到内部的最后一个节点   append附加,追加
const box = document.querySelector('.box');
const newImg = document.createElement('img');
newImg.src = './ad.png';  //添加属性
box.appendChild(newImg);  //box添加子元素

//插入节点 fatherElement.insertBefore(newElement,oldElement); insert插入 
const p = document.querySelector('p');
box.insertBefore(newImg,p); //将img插入在p之前

克隆节点

//Element.cloneNode(); 谁调用克隆谁
Element.cloneNode(false);  //克隆仅自己节点,默认
ELement.cloneNode(true);  //克隆自己及所有子节点

const div = document.querySelector('div');
const newDiv = div.cloneNode();
const firstDiv = div.cloneNode(true);
document.body.appendChild(newDiv);  //仅插入div标签
document.body.appenChild(firstDiv); //插入div及下的所有节点

删除节点

//fatherElement.removeChild();
const div = document.querySelector('div');
div.parentNode.removeChild(div);

移动元素

将某个元素追加到目标标签中;元素在文档中是唯一的

移动端事件touch

touchstart //手指触摸
touchmove //手指滑动
touchend //手指松开
document.addEventListener('touchstart',()=>{
    console.log('touchstart');  //触摸输出
})
documeent.addEventListener('touchmove',()=>{
    console.log('touchmove');  //触摸并滑动输出
})
document.addEventListener('touchend',()=>{
    console.log('touchend');  //触摸结束输出
})
submit事件

当表单进行提交时,就会触发submit事件

去除字符串两端的空格
const str = '    aaa    ';
str.trim(); //aaa

使用子节点获取自己父亲的索引值

<tbody>
	<tr>
    	  <td>1001</td>
          <td>1002</td>
          <td>1003</td>
          <td>1004</td>
          <td>1005</td>
          <td>1006</td>
          <td>
            <a href="javascript:">target</a>
          </td>
    </tr>
</tbody>
//当点击a标签的时候反馈他的父元素td在tr中的索引值
const tbody = document.querySelector('tbody');
tbody.addEventListener('click',(e)=>{
    if(e.target.tagName === 'A'){
        const index = Array.prototype.indexOf.call(
        e.target.parentNode.parentNode.children,
        e.target.parentNode);
        console.log(index); //6
    }
})

//Array.prototype.indexOf.call(父元素的子元素,子元素的目标值)