2010-08-06 7 views

Respuesta

5

Como usted no mencionó cualquier uso de bibliotecas javascript (como jQuery, Dojo), aquí hay algo puro JavaScript.

var txt = document.createTextNode(" This text was added to the DIV."); 
var parent = document.getElementById('div'); 
parent.insertBefore(txt, parent.lastChild); 

o

var link = document.createElement('a'); 
link.setAttribute('href', 'mypage.htm'); 
var parent = document.getElementById('div'); 
parent.insertAfter(link, parent.firstChild); 

Codificación feliz.

+1

'document.getElementById ('# div')' será nulo, es probable que significaba 'documento. getElementById ('div') ' –

+2

Esto es incorrecto. * insertBefore * no es una función global, es un método del prototipo * HTMLElement *. El método correcto es 'parentElement.insertBefore (newElement, childElement)'. –

+0

Ah, mi mal. Gracias. – simplyharsh

2

Si desea usar algo como jQuery se puede hacer algo como esto:

$('#div a').after("Your html element"); 
2

jQuery tiene una bonita, construida en función de esto: después de(), en http://api.jquery.com/after/

En su caso, es probable que desee un selector de la siguiente manera:

$('#div a').after('<p>html element to add</p>'); 

Los ejemplos de código de la El enlace anterior también muestra cómo cargar jQuery si es nuevo para usted.

0

Suponiendo que sólo se está agregando un elemento:

document.getElementById("div").insertBefore({Element}, document.getElementById("div").children[2]); 
3

En lugar de tratar a los niños la <div> 's, al igual que otras respuestas, si usted sabe que siempre desea insertar después del elemento <a>, le confieren una Identificación, y luego se puede insertar en relación con sus hermanos:

<div id="div"> 
    <a id="div_link">Link</a> 

    <span>text</span> 
</div> 

y después inserte su nuevo elemento directamente después de ese elemento:

var el = document.createElement(element_type); // where element_type is the tag name you want to insert 
// ... set element properties as necessary 

var div = document.getElementById('div'); 
var div_link = document.getElementById('div_link'); 
var next_sib = div_link.nextSibling; 

if (next_sib) 
{ 
    // if the div_link has another element following it within the link, insert 
    // before that following element 
    div.insertBefore(el, next_sib); 
} 
else 
{ 
    // otherwise, the link is the last element in your div, 
    // so just append to the end of the div 
    div.appendChild(el); 
} 

Esto le permitirá garantizar siempre que su nuevo elemento siga el enlace.

3
node = document.getElementById('YourID'); 
node.insertAdjacentHTML('afterend', '<div>Sample Div</div>'); 

Opciones disponibles

beforebegin, afterBegin, beforeend, AfterEnd

+0

Esto también tiene un buen soporte para el navegador. Si no planea usarlo en IE más antiguos en combinación con tablas. http://caniuse.com/#feat=insertadjacenthtml – cptnk

Cuestiones relacionadas