I want to show the first 2 letters ie, En
. I want to use Pure JS to finish this. There is no changes whatsoever. I have tried to add the JS in both header and footer, still no change on the site.
HTML:
<a href="#" class="myclassname">English</a>
JS:
var i;
var sheb = document.getElementsByClassName("myclassname");
for(i=0;i<sheb.length;i++) {
if(sheb[i].className == 'myclass') {
sheb[i].innerHTML = sheb[i].innerHTML.substring(0,3);
}
}
You made a mistake in your if
statement; you check if the className is myclass
instead of myclassname
. Also, you should use substring(0,2)
instead of substring(0,3)
.
Apart from those 2 mistakes, it works fine:
var i; var sheb = document.getElementsByClassName("myclassname"); for(i=0;i<sheb.length;i++) { if(sheb[i].className == 'myclassname') { sheb[i].innerHTML = sheb[i].innerHTML.substring(0,2); } }
<a href="#" class="myclassname">English</a>
You have two issues:
There is a mismatch between the class name used in HTML ( myclassname
) and in JavaScript ( myclass
).
Then your are taking up to 3 character with .substring(0,3)
. Here the second argument ( 3
) is the length to take from the string. You have to change that to .substring(0,2)
.
Try the following way:
var i; var sheb = document.getElementsByClassName("myclass"); for(i=0;i<sheb.length;i++) { if(sheb[i].className == 'myclass') { sheb[i].innerHTML = sheb[i].innerHTML.substring(0,2); } }
<a href="#" class="myclass">English</a>
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.