Serge Pedroza
Serge Pedroza

Reputation: 2170

Convert jquery function to Javascript function

I am trying to convert this function but I can't seem to translate a few of the lines successfully.

$('.text').each(function() {
  str = String($(this).html()); #this line
  tot = str.length;
  str = (tot <= max) ? str : str.substring(0,(max + 1))+"..."; #this line
  $(this).html(str); #this line
});

How can I convert this into a javascript function?

Upvotes: 1

Views: 66

Answers (2)

Shirish Maharjan
Shirish Maharjan

Reputation: 502

document.querySelectorAll('.text').forEach(function(el){
var str = el.innerHTML;
var tot = str.length;
...
this.innerHTML = str;
});

Upvotes: 1

Davide Bulbarelli
Davide Bulbarelli

Reputation: 743

Try with this:

document.getElementsByClassName('text').forEach(el => {
   str = el.innerHTML;
   tot = str.length;
   str = (tot <= max) ? str : str.substring(0,(max + 1))+"..."; 
   el.innerHTML = str;
})

Upvotes: 0

Related Questions