I’m having some trouble removing an element that gets added dynamically to the DOM. Everything in the script below works as it is supposed to, with the exception of the remove method inside the mouseleave handler. My guess is that I’m making a mistake with the CSS selector, but I’m not sure what it is. Any help will be much appreciated!
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Index</title>
<link href="/Content/Site.css" rel="stylesheet" type="text/css" />
<script src="/Scripts/jquery-1.5.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function ()
{
$('#myTr').mouseenter(function ()
{
var cell1 = $(this).children(':first');
cell1.css('position', 'relative');
var myDiv = document.createElement('div');
var myChildDiv = document.createElement('div');
myChildDiv.style.position = 'absolute';
myChildDiv.style.height = '20px';
myChildDiv.style.width = '30px';
myChildDiv.style.opacity = '0.6';
myChildDiv.style.background = 'grey';
$(cell1).prepend(myDiv);
$(myDiv).append(myChildDiv);
})
.mouseleave(function ()
{
$(this).remove('td:first-child>div');
});
});
</script>
</head>
<body>
<table>
<tbody>
<tr id="myTr">
<td style="width: 200px;">
Anytown, MA
</td>
</tr>
</tbody>
</table>
</body>
</html>
You could place the element you create into a variable in the scope of your function and then simply call remove() on it… This has the added benefit of not needing to use css selectors to find it again.