Reputation: 5370
I would like the follow code to load a series of "holder" classes. However the after() method seems to be nesting the holders.
Current code
<div class="holder" >
<a href="test.html" class="link">lorem ipsum</a><br />
</div>
<script type="text/javascript">
$(document).ready(function () {
$('.link').click(function (event) {
var newHolder = $('.holder').after()
newHolder.load(this.href);
event.preventDefault();
return false;
});
});
</script>
** Desired output **
<div class="holder"></div>
<div class="holder"></div>
<div class="holder"></div>
<div class="holder"></div>
etc
Upvotes: 0
Views: 114
Reputation: 10607
I think the simplest way to achieve the output you want might be this:
$('.link').click(function(e) {
e.preventDefault();
$(this).parent().after('<div class="holder"></div>').load(this.href);
});
Upvotes: 1
Reputation: 42246
jQuery's .after()
method "inserts content, specified by the parameter, after each element in the set of matched elements". It sounds like the correct API call, for the objective you described.
However, I see two problems with how you are using it.
;
after the after()
call. This could potentially have the effect of causing a JavaScript error which makes the script terminate. You do not pass an argument to the after
call. It is not clear that the way you are using it should return a new holder object. I'm still not completely clear on what you are trying to do, but I think this might work better:
$('.link').click(function (event) {
event.preventDefault();
var linkHref = this.href;
$('.holder').each(function(){
$this = $(this);
var $clone = $this.clone();
$clone.load(linkHref);
$this.after($clone);
});
return false;
});
Can you post a more complete code sample (or jsFiddle) including the HTML DOM sample so we can see what exactly is happening incorrectly?
Upvotes: 1
Reputation: 21388
If you want it to be after the current link, this will take you up the DOM tree one level, to the current div.holder
and then to the next .holder
, then call load.
$('.link').click(function(e) {
var div = $('<div/>',{"class":"holder"}).load(this.href);
$(this).parent().after(div);
e.preventDefault();
});
Edit: Misunderstood, the div needs to be created, yes?
Upvotes: 1