2013-04-20 49 views
0

我想添加一個圖像,做下面的代碼的等價物,但不是創建一個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); 

回答

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

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