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>
?
-
A
span
is an inline -- not even block-inline -- element (by default). I am not sure if it is permissible to put animg
in aspan
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
5 Answers
Reset to default 6Use 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.