[英]Why can't I access to some elements of document.querySelectorAll
I'm new in programming and I would like to understand why I can access to some elements in a certain way and why I can't to some other in the same way.我是编程新手,我想了解为什么我可以以某种方式访问某些元素,而为什么我不能以相同的方式访问其他元素。
There is the code:有代码:
const cImg = document.querySelectorAll('#cImg');
console.log('c :', cImg);
console.log('element : ', cImg['0'].offsetHeight);
cImg.forEach(element => {
console.log('e :', element.clientWidth);
});
I see in the console.log of the "cImg", the elements offsetHeight
and clientWidth
我在“cImg”的 console.log 中看到元素
offsetHeight
和clientWidth
If I'm trying to log ofsetHeilght in the forEach
I get this error如果我试图在
forEach
中记录 ofsetHeilght 我会收到此错误
but if I'm doing it like this: cImg['0'].offsetHeight
I have the correct display "399" and if i want to see the element "clientWidht" in the forEach
it works, I get the display "298"但如果我这样做:
cImg['0'].offsetHeight
我有正确的显示“399”,如果我想在forEach
中看到元素“clientWidht”它可以工作,我得到显示“298”
I don't understand why, because both elements are in the "cImg array".我不明白为什么,因为这两个元素都在“cImg 数组”中。
Someone have an explication?有人解释一下吗?
Thanks a lot.非常感谢。
[edit] [编辑]
To get to the CSS in an element, through javascript, you need to go through element.style
.要通过 javascript 获取元素中的 CSS,您需要通过
element.style
获取 go。
Try尝试
element.style.offsetHeight
[edit 2] No, it's not because to get CSS it's element.style.height and javascript can't get CSS code. [编辑 2] 不,这不是因为要获得 CSS 它的 element.style.height 和 javascript 无法获得 CSS 代码。 Too much wine a Saturday night.
周六晚上酒太多。 :P
:P
[edit 2] [编辑 2]
function displayWidth() { const cImg = document.querySelectorAll('.cImg'); console.log('c:', cImg); if (cImg.length) { console.log('element: ', cImg[0].offsetHeight); cImg.forEach(element => { console.log('e:', element.clientWidth); }); } }
<body onload="displayWidth()"> <div class="cImg"> askldajsldkjasdklasd </div> <div class="cImg"> askldajsldkjasdklasd </div> <div class="cImg"> askldajsldkjasdklasd </div> <div class="cImg"> askldajsldkjasdklasd </div> </body>
Without testing it, but each element can only have their each own unique id (if any).无需测试,但每个元素只能有自己的唯一 ID(如果有)。 What you can use with querySelectorAll is classes (among other things).
您可以与 querySelectorAll 一起使用的是类(除其他外)。 So each person in a group of humans have their own unique name, but all belong the the class
humans
.所以人类群体中的每个人都有自己独特的名字,但都属于 class
humans
。 Change id="cImg"
to class="cImg"
and do use querySelectorAll(".cImg")
instead.将
id="cImg"
更改为class="cImg"
并使用querySelectorAll(".cImg")
代替。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.