Reputation: 279
I just start to use JQuery and I want to add li element in my HTML when I click on a button.
My Html code :
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="css/style.css">
<script type="text/javascript" src="js/index.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<div class="filtres">
<input id="filtre1" type="button" value="filtre 1" onclick="test()">
</div>
<div id="liste">
<ul>
<li>Bonjour</li>
</ul>
</div>
</body>
</html>
And my js file :
function test() {
console.log("On clique");
$("<li>Coucou</li>").appendTo("<ul>");
}
Unfortunately, It doesn't work and I don't understand why.
Do you have any idea ?
Upvotes: 2
Views: 118
Reputation: 1
function test() {
$('#liste > ul').append('<li>Coucou</li>');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="filtres">
<input id="filtre1" type="button" value="filtre 1" onclick="test()">
</div>
<div id="liste">
<ul>
<li>Bonjour</li>
</ul>
</div>
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="css/style.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript" src="js/index.js"></script>
</head>
<body>
<div class="filtres">
<input id="filtre1" type="button" value="filtre 1" />
</div>
<div id="liste">
<ul>
<li>Bonjour</li>
</ul>
</div>
</body>
</html>
Upvotes: 0
Reputation: 1866
Try this:
function test() {
$('ul').append('<li>Hello!</li>');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="liste">
<ul>
<li>Bonjour</li>
</ul>
</div>
<button onclick="test()">append</button>
append() will add an element at the end
Upvotes: 1
Reputation: 337560
The problem is because your selector is incorrect. appendTo('<ul>')
is trying to create a new ul
element in memory and append the li
to that. You instead need to use appendTo('ul')
, without the angle brackets.
I'd also suggest you use unobtrusive event handlers instead of the outdated onclick
attributes. Here's the full example:
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="css/style.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript" src="js/index.js"></script>
</head>
<body>
<div class="filtres">
<input id="filtre1" type="button" value="filtre 1" />
</div>
<div id="liste">
<ul>
<li>Bonjour</li>
</ul>
</div>
</body>
</html>
jQuery(function($) {
$('#filtre1').on('click', function() {
console.log("On clique");
$("<li>Coucou</li>").appendTo("ul");
});
})
Upvotes: 2