Chad
Chad

Reputation: 89

jQuery copy text from span tag to another span tag

Here's what I'm trying to do(slider):Image screenshot

I'm trying to copy the test from the span that has the class of .panel-title to the span with the class of .duplicate-test.

My HTML code is

<div class="item">
  <a href="./">
   <div class="panel-img">
    <img src="_assets_/images/panel-event.png" alt="">
   </div><!-- /.panel-img -->
   <div class="panel-info">
    <div><p class="duplicate-test"></p></div>
    <span class="panel-title">upcoming events</span>
   </div><!-- /.panel-info -->
  </a>
</div><!-- /.item -->

My jQuery code is

$('.duplicate-test').text($(this).find('.panel-title').text());

It is getting the text from all spans with the class of .panel-title. Is there something wrong with my jQuery code?

Upvotes: 0

Views: 917

Answers (2)

Rory McCrossan
Rory McCrossan

Reputation: 337637

The issue is with your DOM traversal and usage of this.

Assuming there's no outer scope of the snippet you've shown, this will refer to the window, not the current .duplicate-test element. To do what you require, you need to pass the text() method a function. From there you can traverse to find the element you want:

$('.duplicate-test').text(function() {
    return $(this).closest('.panel-info').find('.panel-title').text();
});

Working example

Upvotes: 1

Alon Eitan
Alon Eitan

Reputation: 12025

Try this:

$('.duplicate-test').each(function() {
    $(this).text($(this).parent().next('.panel-title').text());
});

Upvotes: 1

Related Questions