How to insert an item before and outside another item?

Asked

Viewed 43 times

0

How to insert an item via Jquery so that it is BEFORE and OUT of a specific item (accepted edits to improve the way you ask).

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

$("#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>Item 1</td>
  </tr>
  <tr>
    <td>Item 2</td>
  </tr>
  <tr id="add-mesa-de-luz-button">
    <td>Botão de adicionar</td>
  </tr>
</table>

The HTML output 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 item add-mesa-de-luz-button, so that it stays that way:

<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>
  • 1

    Utilize before instead of prepand

1 answer

3


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


Prepend

In this method the jQuery will capture the element #add-mesa-de-luz-button and will add the contents before the first element. This function is opposite to the .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

In this method the jQuery will capture the element #add-mesa-de-luz-button and will add the contents before it. This function is opposite to the .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>

Browser other questions tagged

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