예를 들어 일치하는 모든 클래스를 제거하는 쉬운 방법이 있습니까?
color-*
그래서 요소가 있다면 :
<div id="hello" class="color-red color-brown foo bar"></div>
제거한 후에는
<div id="hello" class="foo bar"></div>
감사!
답변
removeClass의 함수 보낸 함수 인수 얻어 jQuery를 1.4 .
$("#hello").removeClass (function (index, className) {
return (className.match (/(^|\s)color-\S+/g) || []).join(' ');
});
라이브 예 : http://jsfiddle.net/xa9xS/1409/
답변
$('div').attr('class', function(i, c){
return c.replace(/(^|\s)color-\S+/g, '');
});
답변
필자는 alterClass라고하는 플러그인을 작성했습니다. 와일드 카드와 일치하는 요소 클래스를 제거하십시오. 선택적으로 클래스를 추가하십시오 : https://gist.github.com/1517285
$( '#foo' ).alterClass( 'foo-* bar-*', 'foobar' )
답변
나는 이것을 정규식을 인수로 취하는 Jquery 플러그인으로 일반화했다.
커피:
$.fn.removeClassRegex = (regex) ->
$(@).removeClass (index, classes) ->
classes.split(/\s+/).filter (c) ->
regex.test c
.join ' '
자바 스크립트 :
$.fn.removeClassRegex = function(regex) {
return $(this).removeClass(function(index, classes) {
return classes.split(/\s+/).filter(function(c) {
return regex.test(c);
}).join(' ');
});
};
따라서이 경우 사용법은 (커피와 자바 스크립트 모두)입니다.
$('#hello').removeClassRegex(/^color-/)
Array.filter
IE <9에는 존재하지 않는 함수를 사용하고 있습니다. 이 WTFPL one 과 같은 폴리 필 에는 Underscore의 필터 기능을 대신 사용하거나 Google을 사용할 수 있습니다 .
답변
다른 곳에서 사용하려면 확장 프로그램을 제안합니다. 이것은 나를 위해 잘 작동합니다.
$.fn.removeClassStartingWith = function (filter) {
$(this).removeClass(function (index, className) {
return (className.match(new RegExp("\\S*" + filter + "\\S*", 'g')) || []).join(' ')
});
return this;
};
용법:
$(".myClass").removeClassStartingWith('color');
답변
우리는 모든 클래스 .attr("class")
를 Array, And Loop & Filter로 가져올 수 있습니다 .
var classArr = $("#sample").attr("class").split(" ")
$("#sample").attr("class", "")
for(var i = 0; i < classArr.length; i ++) {
// some condition/filter
if(classArr[i].substr(0, 5) != "color") {
$("#sample").addClass(classArr[i]);
}
}
답변
@ tremby의 유사 대답 , 여기 코비의 @입니다 대답 접두사 나 접미사 중 하나와 일치하는 플러그인있다.
- 예) 스트립
btn-mini
과btn-danger
아닌btn
경우stripClass("btn-")
. - 예)는 스트립
horsebtn
및cowbtn
하지만btn-mini
나btn
때stripClass('btn', 1)
암호:
$.fn.stripClass = function (partialMatch, endOrBegin) {
/// <summary>
/// The way removeClass should have been implemented -- accepts a partialMatch (like "btn-") to search on and remove
/// </summary>
/// <param name="partialMatch">the class partial to match against, like "btn-" to match "btn-danger btn-active" but not "btn"</param>
/// <param name="endOrBegin">omit for beginning match; provide a 'truthy' value to only find classes ending with match</param>
/// <returns type=""></returns>
var x = new RegExp((!endOrBegin ? "\\b" : "\\S+") + partialMatch + "\\S*", 'g');
// https://stackoverflow.com/a/2644364/1037948
this.attr('class', function (i, c) {
if (!c) return; // protect against no class
return c.replace(x, '');
});
return this;
};