Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Take <span> class and put in <a> attribute jquery

I have html like this.

<span class="gallery-open-item year-icon-Yes 2010">
<a href="/year/none">
</a>
</span>

I need to check using jQuery if span.gallery-open-item has year-icon-Yes class, and if so take the next (for this example is 2010) class and place it in the href attribute like this:

<a href="/year/2010"/>

All this I need in jQuery or JavaScript.

I have done some experiments but I can't take 2010 to normal javascript variable. Any ideas?

Sorry for my English.

like image 913
Tigran Tokmajyan Avatar asked Dec 02 '25 09:12

Tigran Tokmajyan


2 Answers

Here's another approach. Tested, working.

$('.gallery-open-item.year-icon-Yes').each(function(){
    that = this;
    var classes = $(this).attr('class').split(' ');
    $.each(classes, function(i, val) {
        if (val.match(/^y-/gi)) {
            $('a', that).attr('href', function(){
                return this.href.replace('none', val.split('-')[1]);
            });
        }
    });
});

Assumes this markup:

<span class="gallery-open-item year-icon-Yes y-2010">
<a href="/year/none/">
    Test
</a>
</span>
like image 121
artlung Avatar answered Dec 05 '25 01:12

artlung


How about this:

$('span.gallery-open-item.year-icon-Yes > a').each(function(i, elem) {
  $.each($(elem).parent().attr('class').split(' '), function(j, klass) {
    // NOTE: use /^y-([\d]*)$/ if years are prefixed with y-
    if (year = klass.match(/^([\d]*)$/))
      $(elem).attr('href', $(elem).attr('href').replace('none', year[1]));
  });
});

This would iterate over every A tag beneath your SPAN tags and fetch the classes from each parent, search these for a number and replace the "next" part.

Update: Added comments for the case you switch to prefixed years.

Update 2: Now tested and working (using Prototype usually *sigh*).

like image 29
hurikhan77 Avatar answered Dec 04 '25 23:12

hurikhan77



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!