Reputation: 616
i want to read all links in ".vm-video-title"-divs and post them each in the same div. So i made this script:
$('.vm-video-title').each(function(i) {//all divs
$(this).html($(this).html()+$("div.vm-video-title>a").text());//add to div the link
});
but i have the problem that it reads ALL the links of all divs and put them in one div.
example:
<div class="vm-video-title"><a href="...">Text1</a></div>
<div class="vm-video-title"><a href="...">Text2</a></div>
<div class="vm-video-title"><a href="...">Text3</a></div>
output:
<a href="...">Text1</a>Text1Text2Text3
<a href="...">Text2</a>Text1Text2Text3
<a href="...">Text3</a>Text1Text2Text3
wanted output:
<a href="...">Text1</a>Text1
<a href="...">Text2</a>Text2
<a href="...">Text3</a>Text3
Upvotes: 1
Views: 7097
Reputation: 322492
You can select the <a>
elements directly, and use the after()
[docs] method to append the content of each after each one respectively.
$("div.vm-video-title > a").after(function() { return $(this).text(); });
This doesn't do a "destroy then recreate" of the existing elements like the html()
[docs] method will.
Working example: http://jsfiddle.net/CCr9C/
Upvotes: 5
Reputation: 40507
You were almost there. Instead of : $("div.vm-video-title").text()
, which gives you text inside any div
with class vm-video-title
, you need to find a
tag inside current div
and get text from it. We pass this
as context
for selecting a
inside current div
jQuery( selector, [context] )
$('.vm-video-title').each(function(i) {//all divs
$(this).html($(this).html()+$("a", this).text());
});
Upvotes: 2
Reputation: 13496
This should do the job for you,
you need to find the div inside current element in the loop (el).
$('.vm-video-title').each(function(i, el) {
el = $(el);
el.html(el.html()+el.find("a").text());
});
in your code you are adding text() of all matching "a" tags in your divs (i.e. Text1Text2Text3)
Upvotes: 4