小言_互联网的博客

DOM选择器

253人阅读  评论(0)
前言

    对于JavaScript偶读基础语法,我就不记录了,这里记录一下学习DOM选择器。

1.DOM简介

    文档对象模型(Document Object Model,DOM)是一种用于HTML和XML文档的编程接口。它给文档提供了一种结构化的表示方法,可以改变文档的内容和呈现方式。我们最为关心的是,DOM把网页和脚本以及其他的编程语言联系了起来。DOM属于浏览器,而不是JavaScript语言规范里的规定的核心内容。

2.DOM选择器

(1)直接查找标签

document.getElementById             根据ID获取一个标签
document.getElementsByName          根据name属性获取标签集合
document.getElementsByClassName     根据class属性获取标签集合
document.getElementsByTagName       根据标签名获取标签集合

注:
    document.getElementById只能获取一个元素,因为id是唯一的,而剩下的几个,都可以获取多个元素,返回一个列表,也就是js中的数组。
    例如,我们的HTML文件如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>JS_DOM</title>
</head>
<body>
    <div id="i1">我是i1</div>
    <a>第一个a</a>
    <a>第二个a</a>
    <a>第三个a</a>

</body>

    页面效果如下:

获取id=‘i1的元素’

tag = document.getElementById('i1')
<div id="i1">​我是i1​</div>

获取标签为a的所有元素

tags = document.getElementsByTagName('a')
HTMLCollection(3) [a, a, a]0: aaccessKey: ""assignedSlot: nullattributeStyleMap: StylePropertyMap {size: 0}attributes: NamedNodeMap {length: 0}autocapitalize: ""baseURI: "http://localhost:63342/python%E5%AD%A6%E4%B9%A0/%E5%89%8D%E7%AB%AF%E5%AD%A6%E4%B9%A0/js_DOM.html?_ijt=j57msp3qsgpb0nqsti0eo04s0g"charset: ""childElementCount: 0childNodes: NodeList [text]children: HTMLCollection []classList: DOMTokenList [value: ""]className: ""clientHeight: 0clientLeft: 0clientTop: 0clientWidth: 0contentEditable: "inherit"coords: ""dataset: DOMStringMap {}dir: ""download: ""draggable: falsefirstChild: textfirstElementChild: nullhash: ""hidden: falsehost: ""hostname: ""href: ""hreflang: ""id: ""innerHTML: "第一个a"innerText: "第一个a"inputMode: ""isConnected: trueisContentEditable: falselang: ""lastChild: textlastElementChild: nulllocalName: "a"name: ""namespaceURI: "http://www.w3.org/1999/xhtml"nextElementSibling: anextSibling: textnodeName: "A"nodeType: 1nodeValue: nullnonce: ""offsetHeight: 21offsetLeft: 8offsetParent: bodyoffsetTop: 29offsetWidth: 57onabort: nullonauxclick: nullonbeforecopy: nullonbeforecut: nullonbeforepaste: nullonblur: nulloncancel: nulloncanplay: nulloncanplaythrough: nullonchange: nullonclick: nullonclose: nulloncontextmenu: nulloncopy: nulloncuechange: nulloncut: nullondblclick: nullondrag: nullondragend: nullondragenter: nullondragleave: nullondragover: nullondragstart: nullondrop: nullondurationchange: nullonemptied: nullonended: nullonerror: nullonfocus: nullongotpointercapture: nulloninput: nulloninvalid: nullonkeydown: nullonkeypress: nullonkeyup: nullonload: nullonloadeddata: nullonloadedmetadata: nullonloadstart: nullonlostpointercapture: nullonmousedown: nullonmouseenter: nullonmouseleave: nullonmousemove: nullonmouseout: nullonmouseover: nullonmouseup: nullonmousewheel: nullonpaste: nullonpause: nullonplay: nullonplaying: nullonpointercancel: nullonpointerdown: nullonpointerenter: nullonpointerleave: nullonpointermove: nullonpointerout: nullonpointerover: nullonpointerup: nullonprogress: nullonratechange: nullonreset: nullonresize: nullonscroll: nullonsearch: nullonseeked: nullonseeking: nullonselect: nullonselectstart: nullonstalled: nullonsubmit: nullonsuspend: nullontimeupdate: nullontoggle: nullonvolumechange: nullonwaiting: nullonwebkitfullscreenchange: nullonwebkitfullscreenerror: nullonwheel: nullorigin: ""outerHTML: "<a>第一个a</a>"outerText: "第一个a"ownerDocument: documentparentElement: bodyparentNode: bodypassword: ""pathname: ""ping: ""port: ""prefix: nullpreviousElementSibling: div#i1previousSibling: textprotocol: ":"referrerPolicy: ""rel: ""relList: DOMTokenList [value: ""]rev: ""scrollHeight: 0scrollLeft: 0scrollTop: 0scrollWidth: 0search: ""shadowRoot: nullshape: ""slot: ""spellcheck: truestyle: CSSStyleDeclaration {alignContent: "", alignItems: "", alignSelf: "", alignmentBaseline: "", all: "",}tabIndex: 0tagName: "A"target: ""text: "第一个a"textContent: "第一个a"title: ""translate: truetype: ""username: ""__proto__: HTMLAnchorElement1: a2: alength: 3__proto__: HTMLCollection

可见,返回的是一个列表。
将id=‘i1’的内容改为’我是修改后的内容’:

tag.innerText="我是修改后的内容"
"我是修改后的内容"

效果如图:


将第三个超链接改成‘666’

tags[2].innerText='666'
"666"

如图:

(2)间接查找标签

    方法如下:

parentNode          // 父节点
 
childNodes          // 所有子节点
 
firstChild          // 第一个子节点
 
lastChild           // 最后一个子节点
 
nextSibling         // 下一个兄弟节点
 
previousSibling     // 上一个兄弟节点
 
parentElement           // 父节点标签元素
 
children                // 所有子标签
 
firstElementChild       // 第一个子标签元素
 
lastElementChild        // 最后一个子标签元素
 
nextElementtSibling     // 下一个兄弟标签元素
 
previousElementSibling  // 上一个兄弟标签元素

例如,HTML文档如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>JS_DOM_2</title>
</head>
<body>
    <div>
        <div  id="i1">
            c1
        </div>
    </div>
    <div>
        <div>
            c2
        </div>
    </div>
    <div>
        <div>
            c3
        </div>
    </div>
</body>
</html>

查找id='i1’的元素及其父亲元素和孩子元素:

tag = document.getElementById('i1')
<div id="i1">​
            c1
        ​</div>​
tag.parentElement
<div><div id="i1">​
            c1
        ​</div></div>​
tag.childElementCount
0

为其父亲元素添加一个class='c1’的属性:

tag.parentElement.className = 'c1'
"c1".childElementCount
0

结果:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>JS_DOM_2</title>
</head>
<body>
    <div class="c1">
        <div  id="i1">
            c1
        </div>
    </div>
    <div>
        <div>
            c2
        </div>
    </div>
    <div>
        <div>
            c3
        </div>
    </div>
</body>
</html>

增加及删除class:

tag.parentElement.classList.add('c5')
undefined
tag.parentElement.classList.remove('c1')
undefined

结果:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>JS_DOM_2</title>
</head>
<body>
    <div class="c5">
        <div  id="i1">
            c1
        </div>
    </div>
    <div>
        <div>
            c2
        </div>
    </div>
    <div>
        <div>
            c3
        </div>
    </div>
</body>
</html>



#### 写在最后
&nbsp;&nbsp;&nbsp;&nbsp;本文是个人的一些学习笔记,如有侵权,请及时联系我进行删除,谢谢大家.

转载:https://blog.csdn.net/weixin_42567323/article/details/101385207
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场