这是因为getElementById再结合children属性获取的是DOM元素,而querySelectorAll获取的则是NodeList对象元素。前者会随页面DOM结构的变化而变化,比如删除了box中的一个div,这个div就会从children中被“真实地”删掉,childrenlength的计数也会减1。而后者如果删除其中的某个子元素,被删的元素并不会消失,而是变成一个空对象,children1length的计数也不会改变,这样的话 for(var i=0;i<children1length;) 这个循环由于i的值不变(总是等于0),而children1length也不会减少(总是4),这样就变成死循环了(同时也意味着把一个已删除的元素不断重复删除)。
改成这样就没问题了:
for(var i=0;i<children1length;i++){
boxremoveChild(children1[i]);
}
要获取其他文件下的元素,那么当前页面和另外的页面必须有关联才可以。
比如要从iframe的子页面,获取父页面的元素可以这样写:
parentdocumentgetElementById('a1');
比如要从windowopen的页面中,获取父页面的元素可以这样写:openerdocumentgetElementById("a1");
<body style="height: 2000px;">
<div class="c f" onclick="fn()" style="border:10px solid #ccc;height: 80px;color:red;background:rebeccapurple"> 我是div</div>
<script>
let div = documentquerySelector('div');
/ 通过style在行内样式上获取样式 /
/ 使用style获取样式 写的什么 就能获取到什么
不会转成rgb 和 出现其他的样式 /
consolelog('style',divstylecolor )
consolelog('style',divstylebackground )
/ style是获取不到在内部样式上或者外部样式上的样式的 /
// consolelog( divstylecolor )
// / font-size js中要是用驼峰的方式获取 /
// consolelog( divstylefontSize )
/ 使用windowgetComputedStyle可以获取行内、内部、外部的所有样式
但是 获得color是rbg格式的,获取的background是所有属性 /
consolelog( windowgetComputedStyle(div,null)color )
consolelog( windowgetComputedStyle(div,null)fontSize )
consolelog( windowgetComputedStyle(div,null)background )
consolelog( windowgetComputedStyle(div,null)height )
// documentonscroll = function (){
// consolelog(documentdocumentElementscrollTop);
// }
</script>
以上就是关于JavaScript获取子元素全部的内容,包括:JavaScript获取子元素、JS获取其他文件的某个元素、js之获取元素样式等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)