0

I need to get the text inside each 'dd' and place it as a value of the data-description attribute of the related 'a.myClass'. It would be perfect if the data-description attribute is created only if 'gallery-caption' is present.

HTML

<dl>
    <dt>
       <a class="myClass"></a>
    </dt>
    <dd class="gallery-caption">This is my caption</dd>
</dl>

CURRENT JS (non-working)

$(".myClass").each(function(){

     var Caption = $(this).find('dd.gallery-caption').text();

     $(this).attr('data-description', Caption );

});

Thanks for your help

FINAL WORKING SOLUTION

$(".myClass").each(function(){
     var Caption = $(this).parent().next('dd.gallery-caption').text();

     if (Caption && Caption !== ''){
         $(this).attr('data-description', Caption );
     }
});
4

4 回答 4

3

Have you tried

$(this).parents("dl").find('dd.gallery-caption').text();

http://docs.jquery.com/Traversing/parent

于 2013-03-27T16:03:12.133 回答
2

Why don't you just check it before setting it? Also, data attributes can be accessed by using .data("description").

Also, your selector for Caption needs tweaking.

Try this:

$(".myClass").each(function(){

     var Caption = $(this).parents("dl").find('dd.gallery-caption').text();

     if ($(this).data("data-description")) {
         $(this).data('description', Caption);
     }

});

Demo: http://jsfiddle.net/taju4/

于 2013-03-27T16:03:14.447 回答
2

You needed to go a little higher up the chain to find your caption:

$(".myClass").each(function(){
     var Caption = $(this).closest('dl').find('dd.gallery-caption').text();
     if (Caption && Caption !== ''){
         $(this).attr('data-description', Caption );
     }
});

If you have multiple DD/DT's inside the DL then you'll need to use next():

var Caption = $(this).parent().next('dd.gallery-caption').text();
于 2013-03-27T16:03:39.747 回答
1

See dd.gallery-caption is not a children of .myClass, so try this with .next():

var Caption = $(this).parent().next('dd.gallery-caption').text();

Here you traverse up to its parent and then go at next level of dd and find the .gallery-caption class and take the text out of it.

Although same can be achieved with .siblings() too:

var Caption = $(this).parent().siblings('dd.gallery-caption').text();

Here you traverse up to its parent and then get the sibling at same level and find the .gallery-caption class and take the text out of it.

于 2013-03-27T16:03:59.350 回答