How to generate HTML at a specific point on the page?

0

I'm learning to program in JavaScript and jQuery, and I'm having trouble generating HTML code. Given an HTML body how do I insert HTML code inside a specific place?

In the case below I already know how to insert a paragraph at the end of <body> . But I would like to know how to enter for example before <div> or else within <div>Teste1</div> .

<!DOCTYPE html>
<html>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><script>$(document).ready(function(){$(document.body).append($('<p/>').text('Ola'));});</script></head><body><div>Teste1</div><div>Teste2</div><div>Teste3</div><div>Teste4</div></body></html>

Output:

Teste1 Teste2 Teste3 Teste4 Ola     
asked by anonymous 01.03.2018 / 16:46

2 answers

2

$('#um').append('<p>Segundo do Primeiro</p>');
$('body').prepend('<p>No inicio do Body</p>')
$('body').append('<p>No final do Body</p>')
#um{
background: silver;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divid="um">Primeiro</div>
    
01.03.2018 / 16:50
1

When the elements do not have an ID (ID or Classes), this becomes laborious, since you will have to know the position of the element on the screen.

Knowing the position (ranging from 0 to númeroDeElementos-1 ), you can use the nth-child or eq selector.

$(document).ready(function(){
     /* Adiciona no final do Body */
     $(document.body).append($('<p/>').text('Final do Body'));
     
     /* Adiciona dentro da segunda DIV (0 até n-1) */
     $(document.body).find('div:eq(1)').append($('<p/>').text('Na segunda div'));
     
     /**
      * Antes da terceira div.
      * O before adiciona antes do elemento
      */
     $(document.body).find('div:eq(2)').before($('<p/>').text('Antes da 3 div'));
});
body > div {
  background:gray
}

body div p {
  background:orange
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div>Teste1</div>
<div>Teste2</div>
<div>Teste3</div>
<div>Teste4</div>
    
01.03.2018 / 16:55