user2191353
user2191353

Reputation: 53

What can I use to get just one set of text from divs with the same class using jquery?

I have question that I feel should be simple but I am having issues getting the result I need. I can not change the HTML. Any help would be great!

I have a set up like this.

<div class="container">
    <a href="doesn'tmatter" class="myAtag"></a>
    <div class='mydiv'>this is text1</div>
</div>

<div class="container">
    <a href="doesn'tmatter"></a>
    <div class='mydiv'>this is text2</div>
</div>

I am trying to get the text from each of those divs, set it to a var that I can then use to add a data attribute to the above it.

var DivText = $('mydiv').text();
$('.myAtag').attr('data', 'DivTest');

The problem I run into this that the data attribute is then filled with the text from both divs.

<div class="container">
    <a href="doesn'tmatter" class="myAtag" data="this is text1 this this text2"></a>
    <div class='mydiv'>this is text1</div>
</div>

<div class="container">
    <a href="doesn'tmatter" class="myAtag" data="this is text1 this this text2"></a>
    <div class='mydiv'>this is text2</div>
</div>

What can I use/how can I modifiy my jquery to achieve this outcome?

<div class="container">
    <a href="doesn'tmatter" class="myAtag" data="this is text1"></a>
    <div class='mydiv'>this is text1</div>
</div>

<div class="container">
    <a href="doesn'tmatter" class="myAtag" data="this this text2"></a>
    <div class='mydiv'>this is text2</div>
</div>

Upvotes: 1

Views: 53

Answers (1)

adeneo
adeneo

Reputation: 318312

Use a callback to set each data attribute differently

$('.myAtag').attr('data-text', function() {
    return $(this).next('.mydiv').text();
});

FIDDLE

It's usually a good idea to use a key, as in data-whatever
You could also use data(), but that sets the data internally in jQuery and does not add an attribute

Upvotes: 1

Related Questions