Help with Append()

Asked

Viewed 137 times

0

Follows illustration for clarification inserir a descrição da imagem aqui

I’m stuck on a logic and my problem is this, I have this html code:

<ul class="card"></ul>

<button>
Aperteme
</button>

and do an action with this Jquery:

$('button').on('click',function(){
            $('.card').append(`<li> Teste </li>`)
})

The logic is this: I have a button, whenever I click on it he makes an append in mine .card, but what I would like if my .card if you already have an element, instead of creating a new row, it just groups with the existing one. Type that occurs when I use the command .html but with . html it is sub-created and there is only one element and does not return all.

The moment whenever I click it generates a new append, I want q if there is already an append done before, it just groups the append.

  • It wouldn’t just change the append() to appendTo()? $( "<li> teste </li>").appendTo( ".card" )

  • 1

    What do you mean "group"? You want to put a li inside of another li?

3 answers

1

sort of like this

$(document).ready(function(){
    $("button").click(function(){
        $("#card").append('<li><a href="#">Novo Item</a></li>');
    });
});
<!DOCTYPE html>
<html lang="pt-br">
<head>
<meta charset="utf-8">
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
</head>
<body>
    <ul id="card">
    </ul>
    <button type="button">Add</button>
</body>
</html>      

  • No friend, this is already being done... Kept the same result

  • @Raulcesar I read your question again, it became clearer now, I will adjust the code here and send you.

0

Do so:

$('button').on('click',function(){
            $('<li> Teste </li>').appendTo('.card')
})

-1

Use the appendTo function:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <script src="https://code.jquery.com/jquery-3.4.1.js"
        integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=" crossorigin="anonymous"></script>
    <title>Document</title>
</head>

<body>
    <ul id="card"></ul>

    <button id="add">
        Add in List
    </button>
</body>
<script>
    $(document).ready(function () {
        $('#add').click(function () {
            $('<li>New Item</li>').appendTo('#card');
        });
    });
</script>

</html>

Reference: https://api.jquery.com/appendTo/

  • The result was the same as the append friend

  • @Can Raulcesar put together an illustration of how you would like to display this list? I don’t exactly understand your problem.

  • Yes I will update the post and add the table

  • 1

    Understood, now it was clear, in this case I would use the html function and as a function parameter pass a string concatenated with the elements.

Browser other questions tagged

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