It’s something very obvious but I am not able to see it despite looking at very similar issues other people have faced and gotten solved in stackoverflow. I’m hoping it jumps out at you. Please help me figure out why I am not able to insert (or insertAfter) an existing element.
I’ve included my html view file (I’m using codeigniter) with the relevant javascript.
As ever, thanks very much.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>Afterview</title>
<script src="jquery-1.6.4.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
<div class="divm@n.com">
<li>
Click for more details.
<a id="m@n.com" class="detailbtn" href="#detail-id">(Details)</a>
</li>
</div>
</body>
</html>
<script type="text/javascript">
var html_string;
$('.detailbtn').each(function(i){
$(this).click(function(){
html_string='<li>hello</li>';
$('.divm@n.com').insertAfter(html_string).show();
});
});
</script>
I think you want to change your code to use
.after()and fix your class name like this:Change your class name to
<div class="divmncom">to get rid of special characters that are being interpreted differently than you want.And, while you’re cleaning things up, you should get rid of the
html_stringglobal variable, by either removing the need for it entirely or making it a local variable.By way of explanation, it appears that you don’t understand how
insertAfter()works. When you have:it inserts each element that matches the selector
xafter the target represented byy. In your code:html_stringdoes match any existing DOM elements so it doesn’t have a place to do the insertion.Further, the CSS selector
.divm@n.com'may have problems with the@character and will interpret the.in.comas the start of a second class which is not what you want. There are probably ways to escape those special characters and still use them, but it’s much safer code to just stop using them entirely and make your class names be simple class names that don’t need special characters escaped.You should probably read the pages for the two related jQuery methods
.after()and.insertAfter()to make sure you apply the right parameters to the right method for your particular problem. It looks to me like you want to be using.after()instead.