Mihir Ujjainwal
Mihir Ujjainwal

Reputation: 23

Replace a part of text with an element

I was creating a function with JavaScript. The basic motive of the function was to replace some text of an element with an element . I wanted to change the text emoticon with image of the emoticon. But that didn't happen.

I was successful in changing the some part of text, but the image didn't show up - the code for the image did.

e.g.:

Look the Image here

My code:

function comment_emo_change() {
    var comment_content = document.getElementsByClassName("comment_text");
    for (i = 0; i < comment_content.length; i++) {
        var con_cmo = comment_content[i].textContent;
        var new_con_cmo = con_cmo.replace(":)", "<img src='/scripts/smiley-emocone.gif' class='smiley-emocone'></img>");
        comment_content[i].textContent = new_con_cmo;
    }
}
comment_emo_change();

I want the image to appear instead of its code.

Upvotes: 0

Views: 62

Answers (2)

Ramziddin Makhmudov
Ramziddin Makhmudov

Reputation: 114

// Global Variables
var i = con_cmo = new_con_cmo = null;
// Core
function comment_emo_change() {
   var comment_content = document.getElementsByClassName('comment_text');
   for (i = 0; i < comment_content.length; i++) {
       con_cmo = comment_content[i].innerHTML;
        new_con_cmo = con_cmo.replace(':)', '<img src="/scripts/smiley-emocone.gif" class="smiley-emocone"/>');
        comment_content[i].innerHTML = new_con_cmo;
   }
}
// Function call
comment_emo_change();

This worked for me. Hope this works for you as well!

Upvotes: 0

Arg0n
Arg0n

Reputation: 8423

You probably want to use innerHTML instead of textContent.

Upvotes: 3

Related Questions