Abhijith A C
Abhijith A C

Reputation: 530

Replace every <img> tag with itsown custom data attribute

How to replace every occurrence of <img> tag in a html message, with a unicode value stored as a custom attribute.

Sample message:

<img data-uni-val="&#x1F603;" src="path/to/img1.png" class="emoji"/>hello,
<br /> <img data-uni-val="&#1F604;" src="path/to/img2.png" class="emoji"/>

I need to replace every emoji <img> with its unicode value where it stored as custom attribute.

$('<div />')
.html(chatText).find('img.emoji')
.replaceWith('someval').end().html()

Using above code I can find and replace every img's with a string, but not able to replace with data-uni-val.

I tried:

$('<div />').html(chatText).find('img.emoji')
.replaceWith($(this)
.data('data-uni-val')).end().html()

Is there any simple way to solve this?

Upvotes: 2

Views: 365

Answers (5)

King Size
King Size

Reputation: 397

See if this is what you want:

jQuery('.emoji').each(function(){
var str = jQuery(this).attr('data-uni-val');
jQuery(this).replaceWith(str);
});

Upvotes: 0

Ja͢ck
Ja͢ck

Reputation: 173552

The main issue with your code is that the attribute data-uni-val should be accessed using $(this).data('uni-val').

Furthermore, you could just use .replaceWith(fn) to perform the conversion.

$('.emoji').replaceWith(function() {
  return $(this).data('uni-val');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img data-uni-val="&#x1F603;" src="path/to/img1.png" class="emoji"/>hello,
<br /> <img data-uni-val="&#x1F604;" src="path/to/img2.png" class="emoji"/>

Upvotes: 3

Muhammad Atif
Muhammad Atif

Reputation: 1102

$("div img").each(function(){
$(this).removeClass('emoji').addClass($(this).attr('data-uni-val'));
});

Upvotes: 0

Amit
Amit

Reputation: 46323

In jQuery, the .data() function uses a different "name" than the name you use inside the element markup. It's a camelCase without the 'data' and without the hyphens.

Try .data('uniVal')

Upvotes: 2

slash197
slash197

Reputation: 9034

$('.emoji').each(function(){
   var str = $(this).attr('data-uni-val');
   $(str).insertAfter($(this));
   $(this).remove();
});

Upvotes: 1

Related Questions