如何将图像添加到span子元素?

时间:2013-04-20 18:24:22

标签: javascript html image dom

我正在尝试添加一个图像,并在下面执行相当于代码但不是创建一个textnode,我将如何创建一个图像元素?

//create the DOM object

var newSpan = document.createElement('span');

// add the class to the 'span'

newSpan.setAttribute('class', 'ABC');
document.getElementById('text').appendChild(newSpan);   
var selectedTextNode = document.createTextNode(); 
newSpan.appendChild(selectedTextNode);

3 个答案:

答案 0 :(得分:2)

<div id="text"></div>

//create the DOM object

var newSpan = document.createElement('span');

// add the class to the 'span'

newSpan.setAttribute('class', 'ABC');
document.getElementById('text').appendChild(newSpan);

var image = document.createElement("img");
image.src = "http://upload.wikimedia.org/wikipedia/commons/thumb/a/a5/Fairfax-harrison-1913.jpg/100px-Fairfax-harrison-1913.jpg"

newSpan.appendChild(image);

on jsfiddle

答案 1 :(得分:1)

如果我要做很多 Node 创建,我通常会为它编写一个函数,所以我不必重复自己。

//                     String,  Object,  String
function createElement(tagName, attribs, text) {
    var elm = document.createElement(tagName), a;
    if (attribs) // if given
        for (a in attribs) // for each property
            if (attribs.hasOwnProperty(a)) // that is not inherited
                elm.setAttribute(a, attribs[a]); // set attribute
    if (text) // if given
        elm.appendChild(document.createTextNode(text)); // append text
    return elm; // node out
}

现在更容易了;

// create the elements
var span = createElement('span', {'class': 'ABC'}),
    img = createElement('img', {'src': 'http://www.google.com/favicon.ico'});

span.appendChild(img); // put image in span
document.getElementById('text').appendChild(span); // append wherever

答案 2 :(得分:0)

//create the DOM element
var newImg = document.createElement('img');

// add the class to the image
newImg.setAttribute('class', 'ABC');

// set the src URL
newImg.setAttribute('src', 'http://example.com/media/image.png');

// append to the container element
document.getElementById('text').appendChild(newImg);