How do I insert an item before and outside another item?

0

How to insert an item via Jquery so that it stays BEFORE and OUT of another specific item (I accept edits to improve the way you ask).

The following example inserts before, but within the add-mesa-de-luz-button item.

$("#add-mesa-de-luz-button").click(function () {
        $("#add-mesa-de-luz-button").prepend(
          "<tr><td>Item adicionado</td></tr>"
        ); 
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><table><tr><td>Item1</td></tr><tr><td>Item2</td></tr><trid="add-mesa-de-luz-button">
    <td>Botão de adicionar</td>
  </tr>
</table>

The result of the HTML looks like this:

<table>
    <tr>
        <td>Item 1</td>
    </tr>
    <tr>
        <td>Item 2</td>
    </tr>

    <tr id="add-mesa-de-luz-button">
        <tr><td>Item adicionado</td></tr>
        <td>Botão de adicionar</td>
    </tr>
</table>

But I would like it to be inserted before and outside the add-mesa-de-luz-button item, so that it looks like this:

<table>
    <tr>
        <td>Item 1</td>
    </tr>
    <tr>
        <td>Item 2</td>
    </tr>
    <tr><td>Item adicionado</td></tr>
    <tr id="add-mesa-de-luz-button">
        <td>Botão de adicionar</td>
    </tr>
</table>
    
asked by anonymous 16.10.2018 / 16:54

1 answer

3
jQuery has some methods to add content before certain elements, two of them are: .prepend() and .before() .

Prepend

In this method, jQuery will capture the #add-mesa-de-luz-button element and will add the content before the first element. This function is the opposite of .append()

$("ul").prepend("<li>Um</li>")
$("ul").append("<li>Cinto</li>")
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><ul><li>Dois</li><li>Três</li><li>Quadro</li></ul>


Before

Inthismethod,jQuerywillcapturethe#add-mesa-de-luz-buttonelementandwilladdthecontentbeforeit.Thisfunctionistheoppositeof.after()

$("ul").before("Before")
$("ul").after("After")
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<ul>
  <li>Dois</li>
  <li>Três</li>
  <li>Quadro</li>
</ul>
    
16.10.2018 / 17:26