I have a selector that gets all elements by certain condition:
let elements = $("...");
This results in a list of elements whose one of their classes has the same prefix:
some_class_1
, some_class_2
and so on.
I then want to hide all elements that have the same class with addition:
some_class_1extra
, some_class_2extra
For that I want to extract all the classes with this specific prefix, then iterate them and add the extra text and select the elements I want to hide for each.
How can I do it?
The following did not work:
let classes = elements.map(function() {
return (this.className.match(/some_class\d /) || []).pop();
}).get();
CodePudding user response:
Use className
and String.prototype.replace() with a small regex to match your specific class string prefix and replace the match with that same match and your desired suffix.
In this example I'm adding _extra
as suffix, since it's easier to select in CSS :)
document.querySelectorAll('[class^="some_class_"], [class*=" some_class_"]').forEach(el => {
el.className = el.className.replace(/\b(some_class_\d )\b/, "$1_extra");
});
/* Target classes by prefix: */
[class^="some_class_"], [class*=" some_class_"] {
background: red;
}
/* Target classes by suffix: */
[class*="_extra "], [class$="_extra"] {
background: gold;
}
<div >one</div>
<div >two</div>
CodePudding user response:
Please try to do like this.You can select all classes that has some_class
text using $('*[class^="some_class"]')
.
$('*[class^="some_class"]').each((index, item) => $(item).attr('class', `${$(item).attr('class')}extra`));