[英]How to get control in <li> tag inside <ul> tag by JavaScript?
[英]How To Get Child Elements Of tag 'li' In The 'ul' In javascript
當獲取ul中的列表元素時,我們使用類名或標簽獲取元素,並以數組形式返回
var targetImages = document.getElementById("image-list-view").getElementsByTagName("img");
我需要獲取此列表中的元素圖像,而且我似乎在堆棧中
<ul id="image-list-view">
<li>
<a href="#" data-gallery>
<img src="images/pic1.jpg"/>
</a>
</li>
<li>
<a href="#" data-gallery>
<img src="images/pic2.jpg"/>
</a>
</li>
</ul>
編輯
該代碼在站點啟動時工作正常,但targetImages
無法再訪問或引用targetImages
(即無法訪問圖像);
您的代碼有效,您只需要遍歷結果並對圖像進行處理。
getElementsByTagName
返回一個HTMLCollection
,它幾乎就像一個數組。 你可以用同樣的方式遍歷它。
var targetImages = document.getElementById("image-list-view").getElementsByTagName("img"); for (var i = 0; i < targetImages.length; i++) { console.log(targetImages[i]); }
I need to get the element image in this list and i seem to be stack <ul id="image-list-view"> <li> <a href="#" data-gallery> <img src="images/pic1.jpg" /> </a> </li> <li> <a href="#" data-gallery> <img src="images/pic2.jpg" /> </a> </li> </ul>
使用函數querySelectorAll
和這個選擇器ul#image-list-view li img
。
這種方法允許您直接獲取圖像元素並避免第二個函數執行。 此外,如果具有 id
image-list-view
的元素不存在,則此方法不會返回null
值。
var targetImages = document.querySelectorAll("ul#image-list-view li img"); console.log("Count of images: " + targetImages.length);
.as-console-wrapper { max-height: 100% !important; top: 0; } ul { display: none }
<ul id="image-list-view"> <li> <a href="#" data-gallery> <img src="images/pic1.jpg" /> </a> </li> <li> <a href="#" data-gallery> <img src="images/pic2.jpg" /> </a> </li> </ul>
document.querySelectorAll()
返回文檔中與指定選擇器組匹配的元素列表(使用文檔節點的深度優先預序遍歷)。 返回的對象是一個 NodeList。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.