简体   繁体   中英

get image attribute inside element of same class

I have following structure i want to get array of all images src attribute

<div id="selectable"> 
    <li class="x">
        <img src="\images\1.jpg" />
    </li>
    <li class="x">
        <img src="\images\2.jpg" />  
    </li>
    <li class="x">
        <img src="\images\3.jpg" />  
    </li>
</div>

You can do:

var sources = $("#selectable li img").map(function() {
    return this.src;
}).get();

In plain JS, something like this should work:

var images = document.querySelectorAll("#selectable img");
var img_array = [];

for(var i in images) {
    img_array.push(images[i].src);
}

console.log(img_array);

one way to do this with jquery:

$('#selectable').children('li').each(
function(index){
imgSrc[index]=$(this).children('img').attr('src');
}
);

Also:

var img_array = [];
$.each($("#selectable").find('li > img'),function(index,image){


    img_array.push($(image).attr("src"));

});
var srcarray=[];
$( "#selectable .x img" ).each(function( index ) {
  srcarray[index]=$(this).attr('src');
});
alert(srcarray);

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