Issue
remove % and keep testing using jQuery
<div id="top_content">testing %</div> == 0$
I've tried to use this code but it didn't work
$('.top_content:contains("%: ")').each(function(){
$(this).html($(this).html().split("%: ").join(""));
});
top content is an element inside wordpress plugin
thanks for help
Solution
The two reasons your original code didn't work is, first: because you're selecting an element incorrectly; the element has an id attribute but you're using class-based selector (.top_content); and also because you're trying to split the string of text on a character-sequence – "%: " – that isn't present in that string.
While this approach can certainly work:
$('#top_content:contains("%")').each(function() {
$(this).html($(this).html().split(" %").join(""));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="top_content">testing %</div>
It's generally better to use the replace() method to modify text, as it replaces the string in one place, instead of having to remember to remove (with split()) and then join() them together with the desired character.
Below is an approach that uses String.prototype.replace() along with jQuery:
// selecting the element(s), and using the
// anonymous function of the text() method
// to update the text; passing in a reference
// the index of the current element in the
// jQuery collection, and a reference to the
// the current text of that element:
$('#top_content').text(function(i,old){
// here we return the modified string, which
// simply takes the existing string and
// replaces the '%' character with an empty
// string, and then removes any leading/
// trailing white-space with
// String.prototype.trim():
return old.replace('%', '').trim();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="top_content">testing %</div>
Or, without jQuery:
// we need to reference the textContent of this element
// twice, once to set and once to get; therefore we
// cache a reference to the element (in order to avoid
// querying the DOM multiple times):
let topContent = document.querySelector('#top_content');
// here we set the textContent of the element to the
// value returned by using String.prototype.replace()
// to remove the '%' character and replace it with an
// empty string; and removing leading/trailing white-space
// from the string as above:
topContent.textContent = topContent.textContent.replace('%', '').trim();
<div id="top_content">testing %</div>
References:
- JavaScript:
- jQuery:
Answered By - David Thomas Answer Checked By - Terry (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.