hsn0331
hsn0331

Reputation: 394

javascript - how to get img tags from any element?

I want to get img tags attribute values from any element, img tags could be more than 1, and also can be randomized. like,

<div> hellow <img src='icons/smile.png' title=':)'> how are u <img src='icons/smile2.png' title=':D'></div>

I want to grab their title attribute values and then want to store in some var currentHTML; with all existing div data.

and then insert into any element just like $('#div').html(currentHTML);

and output should be like this,

 hellow :) how are u :D

How can I do this?

Thanks in advance.

Upvotes: 1

Views: 368

Answers (2)

DontVoteMeDown
DontVoteMeDown

Reputation: 21475

Try this:

$("img").each(function()
{
    $(this).replaceWith($(this).prop("title"));
});

Fiddle. Its just looping through each image and replacing it (with replaceWith()) with its own title attribute.

UPDATE:

Things got more complex. Check this snippet:

// The text result you want
var currentHTML = "";

// Instead of search for each image, we can search of elements that 
// contains images and you want to get their text
$(".images").each(function()
{
    // Check note #1
    var cloned = $(this).clone().css("display", "none").appendTo($("body"));

    // Here we select all images from the cloned element to what 
    // we did before: replace them with their own titles
    cloned.find("img").each(function()
    {
        $(this).replaceWith($(this).prop("title"));
    });

    // Add the result to the global result text
    currentHTML+= cloned.html();
});

// After all, just set the result to the desired element's html
$("#div").html(currentHTML);

Note #1: Here is what is happening in that line:

Note that in your initial html, the div containing the images received the class images:

<div class="images"> hellow <img src='icons/smile.png' title=':)' /> how are u <img src='icons/smile2.png' title=':D' /></div>

So you can do that on more than one element. I hope this helps.

Upvotes: 4

dannyshaw
dannyshaw

Reputation: 368

Here's a neat little function you can reuse.

$(function(){

  function getImageReplace($el) {
    var $copy = $el.clone();
    $copy.find('img').each(function(){
      $(this).replaceWith($(this).attr('title'));
    });
    return $copy.text();
  }

  //now you can use this on any div element you like
  $('#go').click(function() {
    alert(getImageReplace($('div')));
  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div> hellow <img src='icons/smile.png' title=':)'> how are u <img src='icons/smile2.png' title=':D'></div>   
<button id='go'>Convert images</button>

Upvotes: 2

Related Questions