Search code examples
javascriptcustom-data-attributeselectors-api

Is there a way not to chain querySelectorAll with getElementsByTagName?


I'm trying to get the image from this page: http://m.piperlime.gap.com/product.html?dn=pp438556002&dv=1&vid=1&cid=64413&pid=438556002

Right now my code is:

var image = document.querySelectorAll('[data-index="0"]')[0]
.getElementsByTagName('img')[0].src;

Is there a less cumbersome way to go about this? Assume I need to pull the div that includes data-index="0".

Thanks!

EDIT: the HTML I'm trying to get is this:

<div class="gm_product_item" data-index="0" style="width: 450px; left: 0px; transition: 0ms; -webkit-transition: 0ms; -webkit-transform: translate(0px, 0px) translateZ(0px);">
    <img class="gm_product_itemimg" alt="Mid Rise 11&amp;#34; Skinny Product Image" src="http://www.gap.com/webcontent/0008/860/774/cn8860774.jpg">
</div>

Solution

  • You can target the <img> (which is inside a <div> with data-index="0") directly in your selector:

    var image = document.querySelectorAll('[data-index="0"] img')[0].src