I want to set a Max length of 60 characters in titles, using pure JavaScript. But it does not want to work.
Here is the html
<div class="limiter">
Pandemic deaths are spiraling
out of control since the
opening of the country
and now we test the limiter
</div>
Here is the JavaScript
document.querySelector(".limiter").each(function () {
var a = 60;
var b = document.querySelector(this).text();
if (b.length > a) {
document.querySelector(this).text(b.substring(0, a + 1) + " ...");
} else {
document.querySelector(this).text(b);
}
});
Any idea why it does not work ?
2
Answers
Refer here to learn more Ref: stackoverflow.com/q/9329446/125981
It looks like you’re moving from jQuery to vanilla JavaScript. You’ll notice that the code isn’t transferable. The code looks similar but the syntax is different.
Updating your code:
To pick up an array-like list of nodes you’ll need to use
querySelectorAll
.each
should becomeforEach
. Note there are a few other methods for iterating over the node list butforEach
is the closest match for your use-case. The first argument in its callback is the current iterated element.JavaScript doesn’t have a
text()
function. You need to get/set thetextContent
property directly. (OrinnerText
depending on your needs – here you can see the differences between the two).You need one condition – to change the text if its length exceeds the limit you’ve imposed. In this example I’ve used
slice
and a template string to create the new truncated string.These days its better to move on from
var
and useconst
orlet
to declare your variables.