3.19

Node.hasChildNodes()

返回一个布尔值,判断当前节点是否有子节点。

var _asiaUl = document.getElementById("_asia");
if (_asiaUl.hasChildNodes()) {
    _asiaUl.innerHTML = "";
}

Node.removeChild()

方法接收一个子节点作为参数,用于从当前节点移除该子节点。返回被移除的子节点。

var removeCountry1 = function(id) {
    var _asiaEle = document.getElementById("_asia");
    _asiaEle.removeChild(document.getElementById(id));
}

盒子模型相关属性

Element.clientHeight/clientWidth
返回元素可见部分的高度和宽度:注意包含了 padding 的值
Element.clientLeft/Top
获取元素左边框、顶部边框的宽度

查找相关属性

Element.querySelector()
该方法接收 CSS 选择器作为参数,返回父元素第一个匹配的子元素。

<ul id="_asia">
<li id="_china" class="t2">China&nbsp;<input type="button" id="btn" value="X" onclick="removeCountry1('_china');"/></li>
<li id="_korea" class="t1">Korea&nbsp;<input type="button" id="btn" value="X" onclick="removeCountry1('_korea');"/></li>
<li id="_japan" class="t1 t2">Japan&nbsp;<input type="button" id="btn" value="X" onclick="removeCountry1('_japan');"/></li>
 </ul>
var _ali = document.getElementById("_asia").querySelector(".t1");
console.log(_ali); // _korea

Element.querySelectorAll()
方法接收 CSS 选择器作为参数,返回一个 NodeList 对象,包含所有匹配的子元素。
Element.getElementsByTagName()
注意是标签的参数大小写不敏感
Element.getElementsByClassName()
方法接收类名,返回当前节点所有匹配类名的元素
Element.closest()
方法接收 CSS 选择器作为参数,返回当前元素节点最接近的父元素(从当前节点开始向上遍历)

<div id="_d" class="ddd">
  Here is _d
 <div id="_d1"  class="ddd">
  Here is _d1
  <div id="_d2">
   Here is _d2
   <div id="_d3">
    Here is _d3
   </div>
  </div>
 </div>
</div>

var _d1 = document.getElementById("_d3").closest(".ddd");
console.log(_d1.textContent); // _d1

其他方法

Element.remove()
将当前节点从 DOM 树上删除。

属性操作的标准方法

getAttribute()
setAttribute()
上述两个方法对所有的属性都适用(包含用户自定义的方法)

_abaidu.setAttribute("href","http://www.sina.com");
console.log(_abaidu.getAttribute("href"));

_abaidu.setAttribute("test","xxx");
console.log(_abaidu.getAttribute("test"));

dataset 属性

有时需要在 Html 上附加数据,供 Javascript 脚本使用。一种解决方法是自定义属性。
虽然自己随意定义的属性名可以通过相关的方法进行定义和赋值,但是会使得HTML元素的属性不符合规范,导致网页的HTML代码通不过校验。

更好的解决方法是,使用标准提供的data-*属性。
再使用元素对象的 dataset 属性对自定义的属性进行操作。

注意:data-后面的属性有限制,只能包含字母、数字、连词线(-)、点(.)、冒号(:)和下划线(_)。而且属性名不应该使用大写字母。比如data-helloWorld,我们不这么写,而写成data-hello-world。

在转成dataset的键名的时候,连词线后面如果跟着一个小写字母,那么连词线会被移除,该小写字母转为大写字母,其他字符不变。

console.log(_abaidu.getAttribute("data-hello-world"));
console.log(_abaidu.dataset.helloWorld); // 驼峰命名

猜你喜欢

转载自blog.csdn.net/j94926/article/details/79620220