Home > Software design >  Jquery get image src array
Jquery get image src array

Time:02-14

I'm making a discord bot with discord.js. jQuery get the image src

looked for the most relevant article, but it's different from what I'm trying to do.

I'd like to receive several srcs of img in the span tag by array.

<div >
   <span id="gem00"  data-grade="3" data-item="E595062cGem_000">
     <span >
       <img src="https://xxx/60.png" alt=""> // this src
     </span>
     <span >Lv.5</span>
   </span>
   <span id="gem01"  data-grade="3" data-item="E595062cGem_001">
     <span >
       <img src="https://xxx/50.png" alt=""></span> // this src
     <span >Lv.5</span>
   </span>
</div>
const jewel = $(".jewel_level").text();
const jewel2 = $(".jewel_img").find('img').attr("src");

console.log("jewel : ", jewel, "jewel2 : ", jewel2);

jewel receives both lv.5 and ex) lv.5lv.5. jewel2 only receives one src.

How should I bring it?

console

jewel : Lv.5Lv.5 jewel2 : https://xxx/60.png

CodePudding user response:

The problem with jQuery's .attr() is...

Get the value of an attribute for the first element in the set of matched elements

Instead, you can use jQuery's .map() to transform a collection of elements into an array

const sources = $(".jewel_img > img")
  .map((_, { src }) => src) // extract property
  .get() // get the array out of the jQuery object
  
console.log("sources", sources)
<!-- minified HTML -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.slim.min.js"></script>
<div > <span id="gem00"  data-grade="3" data-item="E595062cGem_000"> <span > <img src="https://xxx/60.png" alt=""> </span> <span >Lv.5</span> </span> <span id="gem01"  data-grade="3" data-item="E595062cGem_001"> <span > <img src="https://xxx/50.png" alt=""></span> <span >Lv.5</span> </span></div>


You may even want to treat the text in a similar way and collect all the data into objects

const data = $(".jewel_btn")
  .map((_, btn) => {
    const $btn = $(btn)
    return {
      image: $btn.find(".jewel_img img").attr("src"),
      level: $btn.find(".jewel_level").text()
    }
  })
  .get()
  
console.log("data", data)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.slim.min.js"></script>
<div > <span id="gem00"  data-grade="3" data-item="E595062cGem_000"> <span > <img src="https://xxx/60.png" alt=""> </span> <span >Lv.5</span> </span> <span id="gem01"  data-grade="3" data-item="E595062cGem_001"> <span > <img src="https://xxx/50.png" alt=""></span> <span >Lv.5</span> </span></div>

  • Related