I have a piece of code that essentially looks like this:
<div class="parent">
<a href="#" class="link"></a>
<div class="text"> Some plain text </div>
</div>
Now I append a href to div.text like this:
$('div.text').each(function(){
$(this).append('<a class="append" href="' + $(this).attr('href') + '"></a>');
});
The problem is that I need to get the href from a.link. How do I go one level up to that href? Obviously 'this' doesn’t work. I also cant call it by class name since there are lots of a.link and they are also dynamically created. I also cant use ‘parent’ or ‘parents’, for some reason it doesn’t work in my script.
.parent()won’t work because theaelement is a sibling, not a parent. You can use.prev()instead:The
.prev()method will return the immediately preceding element. If your markup was to change, you could also use.prevAll(".link"), or.siblings(".link").