I need to shave off a few characters from a certain span. I'll specifically need to target the itemprop attribute. The full element is:
<span itemprop="dateVehicleFirstRegistered" class="wpcm-vehicle-data">03-1973</span>
Currently, it's displaying 03-1973, when I only need 1973. I figured if I couldn't work out where this was being set in the plugin, I could simply use substring to remove the first 3 characters to just show 1973.
The year, of course, varies depending on what the user enters, hence needing to target the itemprop rather than just this one specific case.
It's been a while since I used jQuery. My current attempt is:
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery('span[itemprop="dateVehicleFirstRegistered"]').substring(3);
});
</script>
However i'm getting an error saying it isn't a function. The error:
(index):494 Uncaught TypeError: jQuery(...).substring is not a function
at HTMLDocument.<anonymous> ((index):494)
at i (jquery.js?ver=1.12.4:2)
at Object.fireWith [as resolveWith] (jquery.js?ver=1.12.4:2)
at Function.ready (jquery.js?ver=1.12.4:2)
at HTMLDocument.K (jquery.js?ver=1.12.4:2)
Likely missing something obvious. Any suggestions?
答案 0 :(得分:0)
jQuery('span[itemprop="dateVehicleFirstRegistered"]')
doesn't return a string, so using string methods on it won't work. You need to get the contents of that span as a string, then use the substring method on it, then reset the contents of the span
with the new value.
Additionally, use an each
loop to make the change to every instance:
jQuery(document).ready(function(){
jQuery('span[itemprop="dateVehicleFirstRegistered"]').each(function() {
let myText = jQuery(this).text();
myText = myText.substring(3);
jQuery(this).text(myText);
});
});
答案 1 :(得分:0)
您可以使用拆分功能获取年份。
console.log($('span[itemprop="dateVehicleFirstRegistered"]').text().split("-")[1]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span itemprop="dateVehicleFirstRegistered" class="wpcm-vehicle-data">03-1973</span>