Reputation: 524
This is an extremely odd and simple issue that I've been stuck on now for FAR longer than I care to admit! My slice() function isn't working, anymore. I've checked the syntax a billion times. It seems to have been working at one point, that's the most complicated fact.
jQuery(document).ready(function($){
jQuery("h2.page_title").css('background','lime');
jQuery("h2.page_title").text().slice(2);
});
The file and function are running fine, hence the lime background. However, slice() will not work, or even update through my console. It doesn't matter which element I target in the DOM. I've cleared caches, restarted all WAMP services, etc. I know the real solution is something extremely more stupid, so if you have any tips on what could be causing this, it would be extremely appreciated.
Upvotes: 1
Views: 584
Reputation: 171690
If you want to slice the first 2 characters can use text(function)
to return the resultant. This will also loop over any of that selector and do instance specific slicing for all
jQuery("h2.page_title")
.css('background','lime')
.text(function(_, currTxt) {
return currTxt.slice(2);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2 class="page_title">First heading</h2>
<h2 class="page_title">Second heading</h2>
Upvotes: 0
Reputation: 34197
In my humble opinion the jQuery slice()
is actually a misleading name that leads to confusion as it is not really the same as native JavaScript slice (for strings as you use it here). jQuery slice returns a jQuery object, NOT a string.
jQuery .slice()
falls into the "Traversing and Filtering" category.
"Reduce the set of matched elements to a subset specified by a range of indices."
jQuery slice: https://api.jquery.com/slice/
Native string JavaScript .slice()
on the other hand returns a string
"...extracts a section of a string and returns it as a new string, without modifying the original string."
jQuery("h2.page_title").text().slice(2);
Returns a string starting at index 2 of the text - and you do nothing with that string.
Upvotes: 1
Reputation: 2123
When using slice
the original string isn't changed. It only returns you the sliced string. You should do the assigning yourself -
var str = jQuery("h2.page_title").text().slice(2);
jQuery("h2.page_title").text(str);
or in one row -
jQuery("h2.page_title").text(jQuery("h2.page_title").text().slice(2));
Upvotes: 2