I have the following piece of JQuery code which searches an html document for instances of elements with the class <xyz>-annotation-invisible
and replaces it with <xyz>-annotation-visible
. The catch is that if a particular element already has class <abc>-annotation-visible
, then I want to remove all classes of the form *-annotation-visible
and *-annotation-invisible
and replace them with the class multiple-annotation-visible
. How can I check if a particular element already has <abc>-annotation-visible
?
const urlParams = new URLSearchParams(window.location.search);
const annotationTypes = urlParams.get('annotypes').split(',');
const multipleVisibleClass = "multiple-annotation-visible";
$(document).ready(function () {
for (var i=0; i<annotationTypes.length; i )
{
var annotype = annotationTypes[i];
var annotationVisibleClass = `${annotype}-annotation-visible`;
var annotationInvisibleClass = `${annotype}-annotation-invisible`;
var elem = $(`.${annotationInvisibleClass}`);
if (elem.hasClass(anyVisibleClass)) # not sure how to do this part
{
elem.removeClass(anyVisibleClass);
elem.addClass(multipleVisibleClass);
}
else
{
elem.addClass(annotationVisibleClass);
}
elem.removeClass(annotationInvisibleClass);
}
});
CodePudding user response:
You could use is()
and the attribute ends with selecor :
let elem = $("div");
console.log(elem.is("[class$='-annotation-visible']"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div >test</div>
CodePudding user response:
You can get the classes of the targeted elements, split the classes into array and then manipulate the array to get desired results. Try this
const urlParams = new URLSearchParams(window.location.search);
const annotationTypes = urlParams?.get('annotypes')?.split(',') ?? [];
$(document).ready(function(){
annotationTypes.forEach(annotype => {
let visible = `${annotype}-annotation-visible`;
let invisible = `${annotype}-annotation-invisible`;
let multiple = "multiple-annotation-visible";
$(`.${invisible}, .${visible}`).each(function(){
let arr = [];
$(this).attr('class').split(' ').forEach(cls => {
if(cls === invisible){
arr.push(visible);
}else if(cls === visible){
arr.push(multiple);
}else{
arr.push(cls);
}
});
$(this).attr('class', arr.join(' '));
})
})
});