2013-03-08 23 views
7

Diciamo che abbiamo questo markup:Come ottenere l'elemento successivo usando solo JavaScript?

<!DOCTYPE html> 
<html> 
<head> 
<meta charset="utf8" /> 
<title>project.js</title> 
<script src="project.js"></script> 
<script> 

</script> 
</head> 

<body> 
<h1>some project &mdash; javascript & html tests</h1> 
<hr /> 

    <p> 
     testing 123 
    </p> 
</body> 
</html> 

So che ci sono .prependChild(), .appendChild(), .innerHTML, etc, proprietà e metodi, ma quello che sto cercando è come aggiungere (append) il contenuto dopo la </body> chiusura tag?

Ho bisogno di questo, senza usare jQuery — è possibile?

+0

Penso che la maggior parte dei browser non consente di creare un DOM non valido tramite le funzioni DOM. ('html' può contenere solo 1' head' e 1 'body' e commentare i nodi.Nient'altro.) – Roman

+0

quindi intendendo .. se voglio aggiungere qualcosa' after body' dovrei solo aggiungere il genitore: 'html tag? –

+0

@ZlatanO. Cosa vuoi aggiungere ?! –

risposta

7

Se si utilizza 'id'.you possibile utilizzare queste proprietà:

document.getElementById('id').nextSibling; 
document.getElementById('id').previousSibling; 
+0

questo è l'IT! grazie! –

+1

Vale la pena menzionare, se c'è uno spazio bianco tra gli elementi il ​​'nextSibling' restituirà' undefined'. Vedere questo esempio qui: http://www.w3schools.com/code/tryit.asp?filename=FBONDLQCJA0W –

2

non funzionerà in alcuni browser a causa contenuto dopo body non è 'legale'. In ogni caso, questo sarebbe:

document.body.parentNode.appendChild(document.createTextNode('text after body')); 
document.body.parentNode.appendChild(document.createComment('comment after body')); 

http://jsfiddle.net/yVKk6/ e ispezionare il telaio risultato.

+0

a causa di qualche motivo inspiegabile ho pensato che possiamo aggiungere script dopo l'istruzione '', ma ora ho capito che sono aggiunto/anteposto a 'body' o' head'! –

Problemi correlati