首先说一下这部分我遇到过的面试题
- DOM属于哪一种基本的数据结构(树型数据结构)
- DOM操作常用的API(说到操作,其实就是数据处理,主要也就是增,删,改,查,按这几部分去说常用API即可)
- DOM节点的Attribute和property有什么区别?(其实可以这么说,property是对象在js中的属性,attribute是对象在html中的属性)
一、(增)
- document.createElement(‘元素名’)
- document.createAttribute(‘属性名’)
- document.createTextNode(‘文本节点’)
二、(删)
- parent.removeChild()
三、(改)
3.1改动html的DOM
- parent.replaceChild(newnode,oldnode)
- parent.insertBefore(newnode,parentchildnoed)
- parent.appendChild()
3.2改动内容
- el.innerHTML
- el.textContent
3.3修改属性
3.3.1核心DOM
- elem.getAttribute(‘属性名’),获取属性值
- elem.setAttribute(‘属性名’,‘属性值’)
- elem.hasAttribute('属性名’),判断是否包含属性
- elem.removeAttribute(‘属性名’),移除属性
3.3.2(扩展)
HTML DOM访问属性:一些HTML标准属性都被HTML DOM封装在元素对象中,因此这样的形式=>elem.属性名,用普通对象的方式操作属性也是可以的 - 获取,el.属性名
- 修改,el.属性名 = “值”
- 判断,el.属性名 !=“值”
- 移除,el.属性名 =“”;
四、(查)
4.获取html的dom元素
4.1.1按html查找(4种)
- 按id,document.getElementById(‘id’)
- 按标签名,parent.getElementsByTagName(“标签名”),注意这个是获取的一个数组
- 按name属性,document.getElementsByName(“name”)//查表单
- 按class名称,parent.getElementsByClassName(‘class名称’)
4.1.2按HTML中css选择器查找
- 仅查找一个元素,parent.querySelector(‘selector’)
- 找多个元素,parent.querySelector(‘selector’)
备注:查找语句之前有document的是要强制使用document,是parent的则表示,是要查找元素的祖先元素即可
4.2按节点关系查找
父子关系:
- node.parentNode
- node.childNodes
- node.firstChild
- node.lastChild
兄弟关系
- node.previousSibling
- node.nextSibling
(值得注意的是,因为是节点,网页中一切都是节点,甚至看不见的换行符和空字符也是文本节点,因此会造成一定的干扰,看下面代码)
//html代码
< button id="btn" >< /button >
< div >
xxx
< /div >
//js代码
let btn = document.getElementById('btn')
let btntype = btn.nextSibling
console.log(btntype)
//你们认为会打印什么,是不是div
//如果是div就错了,其实是#text,因为<button>和<div>之间还有看不见的文本
4.3 按元素树查找
注意:ie9+支持
父子关系:
- node.parentElement
- node.children
- node.firstElementChild
- node.lastElementChild
兄弟关系
- node.previousElementSibling
- node.nextElementSibling
五、
5.1 el.nodeType
就说一下通常遇到的值吧
- 9,代表el是document
- 1,代表el是element
- 2,代表el是attribute
- 3,代表el是text
5.2 el.nodeName
- el是document,其值就是#document
- el是element,其值就是全大写的标签名
- el是attribute,其值就是属性名
- el是文本,其值就是#text
六、BOM相关问题
其主要的知识点就是navigator、screen、location、history
- navigator 对象包含有关浏览器的信息
- screen设备屏幕大小
- location 包含有关当前 URL 的信息
- history 对象包含用户(在浏览器窗口中)访问过的 URL
6.1如何检测游览器的类型
let ua = navigator.userAgent
let isChrome = ua.indexOf('Chrome')
6.2拆解url的各个部分
-
location.hash 返回一个URL的锚部分
-
location.host 返回一个URL的主机名和端口
-
location.hostname 返回URL的主机名
-
location.href 返回完整的URL
-
location.pathname 返回的URL路径名。
-
location.port 返回一个URL服务器使用的端口号
-
location.protocol 返回一个URL协议
-
location.search 返回一个URL的查询部分