DOM节点操作

TIP:对于添加事件来说,可以脚本中编写添加事件循环,减少代码量,增加效率
if ( window . getComputedStyle )
// 通过属性的有无进行判断
console . log ( window . getComputedStyle ( a ). fontSize );
// ie 不支持
else
console . log ( a . currentStyle . color );
// 低版本 ie 支持,高版本浏览器不支持。
新建节点并且插入:
var text2 = document . createElement ( "p" );
text2 . innerHTML = "lalalallalalla" ;
var a = document . getElementById ( "div" );
a . appendChild ( text2 );
// 把一个子元素追加到父元素后面
console . log ( text2 );
var text1 = document . getElementById ( "text1" );
var text3 = text1 . cloneNode ( true );
// 克隆方法
// a.appendChild(text3);
a . insertBefore ( text2 , text1 );
// 加到前面,属性:新增的元素和在哪个元素前
获取节点:
用document.body来对body进行操作
console. log ( ul . firstElementChild );
// 只获取元素节点
console. log ( ul . firstChild );
// 空格和换行也默认为一个元素,会出错
var li2 = document . getElementById ( "li2" );
console. log ( li2 . parentNode );
console. log ( ul . childNodes );
console. log ( ul . children );
console. log ( li2 . ownerDocument );
console. log ( ul . ownerDocument );
// 同级
console. log ( li2 . previousSibling );
console. log ( li2 . previousElementSibling );
console. log ( li2 . nextSibling );
console. log ( li2 . nextElementSibling );
console. log ( ul . attributes );

删除节点和替换:
function remove () {
text = document . getElementById ( "text" );
document . body . removeChild ( text );
}
var n = document . createElement ( "p" );
n . innerText = " 替换 " ;
document . body . replaceChild ( n , text );

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值