I'm new to JS/jQuery!
I have a plugin who create entries when members submit a form, entries are displayed in a WordPress page.
I want to remove the last comma from div critselect
in a WordPress page. So, after CRM
comma must to be removed.
What I'm doing wrong? I'm beginner!
/*This code are in a WordPress page, on top page*/ jQuery(function($) { $('.critselect').each(function() { var xContents = $(this).contents(); xContents[xContents.length - 1].nodeValue = ""; }); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <!--This code are in a WordPress page --> <div class="critselect"> <h4>MY ENTRIES</h4> Marketing, Retails / Call center, Office / Back-office / CRM, </div>
jQuery(function($) {
$('.critselect').each(function() {
var xContents = $(this).html();
var lastCommaPos = xContents.lastIndexOf(',');
$(this).html(xContents.substring(0, lastCommaPos));
});
});
var div = document.getElementsByClassName('critselect')[0];
var str = div.innerHTML;
var position = str.lastIndexOf(",")+1;
var div.innerHTML = str.substring(0,position - 1) + str.substring(position, str.length);
If there might be whitespace at the end and/or there might not be a trailing comma at all, a regular expression is a good way to go.
document.querySelectorAll('.critselect').forEach(el => {
el.innerHTML = el.innerHTML.replace(/,\s*$/, '');
});
It's even better if you place the list in its own element. That way you can be certain you're only editing the list, not anything else in the div.critselect
.
<div class="critselect">
<h4>MY ENTRIES</h4>
<span>Marketing, Retails / Call center, Office / Back-office / CRM,</span>
</div>
document.querySelectorAll('.critselect > span').forEach(el => {
el.innerHTML = el.innerHTML.replace(/,\s*$/, '');
});
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.