0

我正在尝试添加图像并执行与下面的代码等效的操作,但不是创建文本节点,而是如何创建图像元素?

//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);
4

3 回答 3

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);

jsfiddle上

于 2013-04-20T18:29:01.757 回答
1

如果我要做很多节点创建,我通常会为它编写一个函数,这样我就不必重复自己了。

//                     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
于 2013-04-20T18:43:21.300 回答
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);   
于 2013-04-20T18:28:31.170 回答