最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript putting an image in a span - Stack Overflow

programmeradmin1浏览0评论

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>?

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>?

Share Improve this question asked Aug 2, 2011 at 17:07 SebastianSebastian 3,62818 gold badges63 silver badges95 bronze badges 2
  • A span is an inline -- not even block-inline -- element (by default). I am not sure if it is permissible to put an img in a span either because of HTML (certain restrictions based on elements) or CSS rules (certain restrictions based on CSS attributes?). I would like to see both of these issues addressed in an answer, even if accepted by browsers. – user166390 Commented Aug 2, 2011 at 17:10
  • 1 span is an inline element. img is a block level element. block level elements should not go in inline elements but most browsers will let you anyway. For patibility it's a bad idea. – Joseph Marikle Commented Aug 2, 2011 at 17:13
Add a ment  | 

5 Answers 5

Reset to default 6

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)

  1. 暂无评论