Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
92
rated 0 times [  95] [ 3]  / answers: 1 / hits: 23898  / 10 Years ago, mon, august 11, 2014, 12:00:00

I have the following code which looks at each div with class .comment and shortens the text if more than 100 characters. Using JQuery.



Question is how to convert to native javascript, I can't find equivalents for .each() or $(this)



var showChar = 100;
var ellipsestext = ...;
var moretext = more;
var lesstext = less;
$('.comment').each(function() {
var content = $(this).html();

if(content.length > showChar) {

var c = content.substr(0, showChar);
var h = content.substr(showChar-1, content.length - showChar);

var html = c + '<span class=moreellipses>' + ellipsestext+ '&nbsp;</span><span class=morecontent><span>' + h + '</span></span>';

$(this).html(html);
}

});


Is this possible?


More From » jquery

 Answers
17

You're not going to find a native equivalent to $(this) because that is the jQuery function. There wouldn't be any reason to write the $ function if it already existed natively.



As for the .each part, you can work with any array like this:



var $comments = $('.comment');
comments.forEach(function(comment) { ... });


or using a simple for loop:



for (var i = 0, len = $comments.length; i < len; i++) {
var comment = $comments[i];
}


If you want to remove jQuery entirely, you'll need to get your elements using document.getElementsByClassName. This will return an HTMLCollection which does not have the forEach function so you'll need to use a for loop like above.



Also note that you won't have access to the .html function. Instead, you can access and modify it with the .innerHTML property of each node.



var comments = document.getElementsByClassName('comment');
for (var i = 0, len = comments.length; i < len; i++) {
var comment = comments[i];
var content = comment.innerHTML;
...
comment.innerHTML = html;
}


Update: 2019-12-02



Nowadays it is more common to use document.querySelectorAll for querying elements and you can use Array.from if you would like to convert the NodeList to an array.





function boldComments() {
const comments = document.querySelectorAll('.comment');
comments.forEach(comment => {
comment.innerHTML = '<b>' + comment.innerHTML + '</b>';
})
}

document.querySelector('button').addEventListener('click', boldComments);

<ul>
<li class=comment>Comment A</li>
<li class=comment>Comment B</li>
<li class=comment>Comment C</li>
<li class=comment>Comment D</li>
</ul>
<button>Bold comments</button>




[#69825] Friday, August 8, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
eanskylerg

Total Points: 524
Total Questions: 107
Total Answers: 100

Location: Colombia
Member since Mon, May 2, 2022
2 Years ago
;