IQ246 IQ246 - 5 months ago 8
HTML Question

Append buttons to a list by using hover

I have a ul list of elements

<ul id="list">
<li></li>
<li></li>
<li></li>

</ul>


I want by using hover to append two buttons on a particular li from this list, when I am on that li elements buttons to show, and when i am off buttons to hide. Here is my code:

$("ul").find("li").hover(
function() {
$('li').append('<button id="but1">Button1</button>'
+ '<button id="but2">Button1</button>');},
function(){
$('#but1').remove();
$('#but2').remove();
});


And this is another try but it appends the buttons at the and of the list not in a particular li from ul list

$('#list').each(function(){
console.log($(this));
$(this).hover(
function() {
$(this).append('<button id="but1">Button1</button>' + '<button id="but2">Button1</button>');
},
function(){
$('#but1').remove();
$('#but2').remove();
}

);


});

Answer

Try it like this

$("#list li").hover(function() {
  $(this).append('<button id="but1" >button1</button><button id="but2">button2</button>');
}, function() {
  $(this).empty();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="list">
  <li></li>
  <li></li>
  <li></li>

</ul>