1. 程式人生 > >js面試,JS-WEB-API相關問題

js面試,JS-WEB-API相關問題

首先說一下這部分我遇到過的面試題

  • 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