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

Asked

Viewed 66 times

0

I’m learning to code in Javascript and jQuery, and I’m having trouble generating HTML code. Given an HTML body how do I insert HTML code within 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 insert for example before the <div> or within the <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>

Exit:

Teste1
Teste2
Teste3
Teste4

Ola

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>
<div id="um">Primeiro</div>

1

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

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

$(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>

  • I did not know this of id, the intention is to make it as simple as possible, in the event of the above answer I would put id in the body

  • 1

    @Viniciusmorais the ideal is to add the ID’s where you want to manipulate. This is easier. When you have a large project, you may end up "getting lost" with the amount of elements. That’s why you can add a id="myId" or class="myClass"

Browser other questions tagged

You are not signed in. Login or sign up in order to post.