开发者

Javascript putting an image in a span

开发者 https://www.devze.com 2023-03-24 11:44 出处:网络
My code, which should put an 开发者_高级运维image in the <span> is this: document.getElementById(\"f_name_mark\").innerText = \"<img src=\'images/icons/tick.png\' class=\'mark\'>\";

My code, which should put an 开发者_高级运维image in the <span> is this:

document.getElementById("f_name_mark").innerText = "<img src='images/icons/tick.png' class='mark'>";

However, the output is <img src='images/icons/tick.png' class='mark'> as a text string.

Is it that you can't put an image in a <span>?


Use InnerHTML instead of innerText

Innerhtml and Innertext properties

Unlike InnerText, though, InnerHtml lets you work with HTML rich text and doesn't automatically encode and decode text. In other words, InnerText retrieves and sets the content of the tag as plain text, whereas InnerHtml retrieves and sets the same content but in HTML format

Span is inline element and image is block element, you can set the display of span element to block or use div to handle it.

document.getElementById("f_name_mark").innerHTML = "<img src='images/icons/tick.png' class='mark'>";


innerHTML is there for a reason :) Try

document.getElementById("f_name_mark").innerHTML = "<img src='images/icons/tick.png' class='mark'>";


Don't use innerHTML or innerText. Instead, create the img element, set the attributes and append them to your span.

var img = document.createElement('IMG');

img.setAttribute('src', 'images/icons/tick.png');
img.setAttribute('class', 'mark');

document.getElementById("f_name_mark").appendChild(img);


document.getElementById("f_name_mark").innerHTML = "<img src='images/icons/tick.png' class='mark'>";


Use the innerHTML attribute, not innerText. It will be parsed and displayed as HTML, whereas innerText will just display as text.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号