insanewolfhd
insanewolfhd

Reputation: 81

JavaScript Replacing Text With HTML Not Working?

So I'm trying to get my website to find certain text and replace it with an <img> tag using this code...

function Emote() {
    var stringg = document.getElementsByClassName("Post").innerHTML;
    var resolutionn = stringg.replace("xD", "<img src='Icons/xD.gif' width='100px' height='100px' />")
    document.getElementsByClassName("demo").innerHTML = resolutionn;
}
Emote();

When I debug with Firebug it outputs this...

enter image description here

Upvotes: 0

Views: 69

Answers (2)

CoderPi
CoderPi

Reputation: 13211

The return-value of document.getElementsByClassName("Post").innerHTML is undefined.

That because document.getElementsByClassName is retouring an array, not a single Element.

Use document.getElementsByClassName("Post")[0].innerHTML to access the first:

<script>
    function Emote() {
        var stringg = document.getElementsByClassName("Post")[0].innerHTML;
        var resolutionn = stringg.replace("xD", "<img src='Icons/xD.gif' width='100px' height='100px' />")
        document.getElementsByClassName("demo").innerHTML = resolutionn;
    }

    window.addEventListener("load", Emote);
    // or window.onload = Emote();
</script>

Upvotes: 1

JCOC611
JCOC611

Reputation: 19709

The function getElementsByClassName returns an array of elements, rather than a single element. Arrays do not have the property innerHTML, thus such will be undefined.

If you want to apply this function to the first element matching the class, use:

document.getElementsByClassName("Post")[0].innerHTML

instead.

Upvotes: 3

Related Questions