I'm trying to get jQuery to check all data-filter inside this list, in case it finds a space between word, it should be replaced with ", ." (I need those to be classes).
This is what I tried, but when I check the console, it says "replace is not a function".
HTML
<ul class="filter-list" data-option-key="filter">
<li>
<a data-filter=".class one" class="" href="#filter">class one</a>
</li>
<li>
<a class="" href="#filter" data-filter=".class two">class two</a>
</li>
<li>
<a class="" href="#filter" data-filter=".class three">class three</a>
</li>
</ul>
jQuery
$('.filter-list a[data-filter]').each(function () {
$(this).replace(/\s/g,", .");
});
Basically, when jQuery finds ".class three" , it should replace it with ".class .three" .
You can use .attr() to do it
$('.filter-list a[data-filter]').attr('data-filter', function (i, attr) {
return attr.replace(/\s+/g, ", .");
});
Demo: Fiddle
Your code fails because inside each()
handler, this
refers to the dom element and $(ths)
returns a jQuery object which does not have the replace method
In your code:
$('.filter-list a[data-filter]').each(function () {
$(this).replace(/\s/g,", .");
});
$(this)
is a DOM element. You can get the text by $(this).text()
. So your code can be something like:
$('.filter-list a[data-filter]').each(function () {
$(this).text($(this).text().replace(/\s/g,", ."));
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.