2013-04-20 4 views
0

Я пытаюсь добавить изображение и сделать эквивалент кода ниже, но вместо создания текстового блока, как создать элемент изображения?Как добавить изображение в дочерний элемент span?

//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 
Смежные вопросы