简体   繁体   中英

How To Get Child Elements Of tag 'li' In The 'ul' In javascript

When getting the list elements in ul, we use get element by class name or tag and are returned in an array

var targetImages = document.getElementById("image-list-view").getElementsByTagName("img");

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>

EDIT

Sorry i didnt explain the problem with the code. 控制台镀铬

the code works fine when the site starts but targetImages can no longer be accessed later or referenced ie (images cannot be accessed);

Your code works, you just need to loop thru the results and do something with the images.

getElementsByTagName returns anHTMLCollection , which is almost like an array. You can loop thru it the same way.

 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>

Use the function querySelectorAll along with this selector ul#image-list-view li img .

This approach allows you to get the image elements straightforward and avoid a second function execution. Further, this approach doesn't return null value if the element with id image-list-view doesn't exist.

 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>

Resource

  • document.querySelectorAll()

    Returns a list of the elements within the document (using depth-first pre-order traversal of the document's nodes) that match the specified group of selectors. The object returned is a NodeList.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM