Take the <span> class and add the <a> jquery attribute

I have html like this.

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

I need to check with jQuery if there span.gallery-open-itemis a class year-icon-Yes, and if so, take the next class (2010 for this example) and put it in the attribute hreflike this:

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

All this I need in jQuery or JavaScript.

I have done some experiments, but I cannot take 2010 into a regular javascript variable. Any ideas?

Sorry for my English.

+3
source share
3 answers

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 will iterate over each A tag under your SPAN tags and select classes from each parent, search for them for a number and replace the “next” part.

: , .

2: ( Prototype * sigh *).

+1

. , .

$('.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]);
            });
        }
    });
});

:

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

. span, gallery-open-item, year-icon-Yes. , span. , . , a span, URL.

$(document).ready(function() {
    $('span.gallery-open-item.year-icon-Yes').each(function() {
        var classNames = $(this).attr('class').split(' ');
        for (var i = 0; i < classNames.length; i++)
        {
            if (!isNaN(classNames[i]))
            {
                var year = classNames[i];
                $(this).find('a').attr('href', '/year/'+year);
                break;
            }
        }
    });
});

. , , y-xxxx:

$(document).ready(function() {
    $('span.gallery-open-item.year-icon-Yes').each(function() {
        var classNames = $(this).attr('class').split(' ');
        for (var i = 0; i < classNames.length; i++) {
            var year = classNames[i].substring(2);
            if (!isNaN(year)) {
                $(this).find('a').attr('href', '/year/' + year);
                break;
            }
        }
    });
});
+1

Source: https://habr.com/ru/post/1749752/


All Articles