1

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

3 Answers 3

4

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/

Sign up to request clarification or add additional context in comments.

Comments

3

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)

Comments

1

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());
});

2 Comments

using "this" is always confusing in js, using a named variable is recommended wherever possible. function(i, el) in this case.
@patrick's method (after) is better as it will not recreate dom elements.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.