开发者

jQuery - Transfer class to another element if the class has specific word in it?

I have this problem that i want to transfer specific ( yet not that specific ) classes from element to another.

this:

<span>
   <span class="THIS-something-something anotherClass"></span>
</span>

into:

<span class="THIS-something-something">
   <span class="anotherClass"></span>
</span>

Basic idea is that if you write a class in that inner span that has specific word "THIS" it would get transfered to the outer span ( the outer span is generated there with .wrap )

class with "THIS" is a class that has like.. 20 different variations ( THIS-something-something, THIS-something-anything, THIS-and-that ..and so on.. ) and "anothe开发者_运维百科rClass" is totally random class and there would possibly be multiple of those as well..depending on how many i would like to insert.

I have no idea how that would go down.. Am i maybe thinking about this all wrong?

I can only make it so that all classes get copied to the outer span and then i would remove all classes from the inner span.. but that kinda defeats all purposes as it doesnt leave "anotherClass" and it copies that to the outer element...


Try this:

$('span > span').each(function() {
    var all = $(this).attr('class').split(' ');
    for (var i = 0; i < all.length; ++i) {
        var cls = all[i];
        if (cls.indexOf('THIS-') == 0) {
            $(this).parent().addClass(cls);
            $(this).removeClass(cls);
        }
    }
});

This may have problems relating to order of processing, hence why the selector requires a span inside another span.


$('span[class|="THIS"]').removeClass(function (index, class) {
    var thisclass=class.match(/THIS-[^\s]+/g).join(' ');
    $(this).parent().addClass(thisclass);
    return thisclass;
});

I can't test it right now, but later I will post a jsFiddle. The regex should be worked on, I just wanted to give you an outline.

The baseline is the usage of .removeClass() with a function and the Attribute Contains Prefix Selector [name|="value"].

UPDATE: fixed the code and added Demo. The code grabs all the classnames starting with THIS- on spans and moves them to their parent (you can run it after wrap() or get rid of my selector and use yours like $(myselector).wrap(mystuff).removeClass(...);).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜