Search code examples
javascriptreplaceinnerhtml

innerHtml Replace insert image Javascript


The below Js Code is working. I want to add a picture here. If the value is 0 then x.png is 180 then y png.

how can I do that. I will be glad if you help. Thank you

var Bearing = document.getElementById("rptAracDetay_Label28_0");
if (Bearing.innerHTML.replace(':   ', '') == '0') { 
    document.getElementById("rptAracDetay_Label28_0").innerHTML = ':   North';
}
else if (Bearing.innerHTML.replace(':   ', '') == '180') { 
    document.getElementById("rptAracDetay_Label28_0").innerHTML = ':   South';
}

Solution

  • I guess you want to add an img element image after your innerHTML text.

    If that is the case,

    var Bearing = document.getElementById("rptAracDetay_Label28_0");                    
    if (Bearing.innerHTML.replace(':   ', '') == '0') { 
        Bearing.innerHTML = ':   North'; 
        var img = document.createElement('img'); 
        img.src = 'https://xyz/x.png'; 
        Bearing.appendChild(img); 
    }
    else if (Bearing.innerHTML.replace(':   ', '') == '180') {
        Bearing.innerHTML = ':   South'; 
        var img = document.createElement('img'); 
        img.src = 'https://xyz/y.png'; 
        Bearing.appendChild(img); 
    }
    

    Upvote if you find it useful.