how to store all <img> tags in one array using jquery

Discussion in 'jQuery' started by pnsrinivasreddy, Aug 29, 2012.

  1. #1
    Hi,

    I have table in a div which contains lot of html elements like this.

    <div id="result">
    <table>
    <tbody>
    <tr>
    <td><img src="images/a.gif" /></td>
    <td><p>sample text</p></td>
    </tr>
    <tr>
    <td><a href="b.gif" /></td>
    <td><p>sample text <img src="images/c.gif" /></p></td>
    </tr>
    <tr>
    <td><p>TEXT</p></td>
    <td><p><img src="images/D.gif" /></p></td>
    </tr>
    </tbody>
    </table>
    </div>

    Now I want to find all the "img" tags in the table and then to store in an array. I am trying with the following code.

    var imagesArray = $("#result").find("img").map(function()
    {
    return $(this).html();
    }).get();

    I know its wrong with the img tags But I have used the same code to load all the table elements in a div. Its not working with img tags. I know its because the image tag doesn't contain any text. So please guide me how can I store all img tags in an array.

    all I need is like this:

    imagesArray = ["<img src="images/a.gif" />","<img src="images/b.gif" />","<img src="images/c.gif" />","<img src="images/d.gif" />"]
     
    pnsrinivasreddy, Aug 29, 2012 IP
  2. artus.systems

    artus.systems Well-Known Member

    Messages:
    87
    Likes Received:
    1
    Best Answers:
    1
    Trophy Points:
    103
    #2
    Instead of getting entire html you can get the src and append img tag later.

    var imagesArray = $("#result").find("img").map(function()
    {
    return $(this).attr("src");
    }).get();
    
    for (i=0; i<imagesArray .length; i++) {
    		
      	var t = "<img src='" + imagesArray [i] + "'/>";
    	alert(t);
    	}
    
    
    Code (markup):
    Hope this helps.
     
    artus.systems, Aug 30, 2012 IP
  3. pnsrinivasreddy

    pnsrinivasreddy Peon

    Messages:
    3
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Thanks so much for your reply. But I need it as html as the img tag contains some dynamic id's. So please help me if there is a way to achieve this.

    Srinu
     
    pnsrinivasreddy, Aug 30, 2012 IP
  4. pnsrinivasreddy

    pnsrinivasreddy Peon

    Messages:
    3
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #4
    Hmm got it..thnx to e_i_pi:

    [TABLE]
    [TR]
    [TD="class: number"][/TD]
    [TD="class: content"]Try this:
    var imagesArray = $("#result").find("img").each(function(index)
    {
    imagesArray = $(this).clone().wrap('<p>').parent().html();
    );
    [/TD]
    [/TR]
    [/TABLE]

    -Srinu
     
    pnsrinivasreddy, Sep 1, 2012 IP