I can shorten the innerHTML of an element selected by its Id using either slice or substring (I'm not sure of the difference between the two, but both do what I want) using this code:
<p id="demo">The quick brown fox jumps over the lazy dog</p>
<p id="demo2" class="demo">The quick brown fox jumps over the lazy dog</p>
let text = document.getElementById("demo").innerHTML;
document.getElementById("demo").innerHTML = text.slice(0, 9);
which outputs as
The quick
The quick brown fox jumps over the lazy dog
However, I can't get it to work on several elements containing the same class. I have tried this:
let text = document.getElementsByClassName('demo');
for (let i=0; i < text.length; i ) {
text.innerHTML.slice(0, 9);
}
But on Codepen it just says "TypeError: elements.innerHTML is undefined".
What am I missing, please?
CodePudding user response:
Using vanilla javascript you can't change all elements at once. Instead, you need to iterate through them. Furthermore, just calling slice
on the innerHTML
won't change it, you need to assign the value.
let texts = document.getElementsByClassName('demo');
for (let i=0; i < texts.length; i ) {
texts[i].innerHTML = texts[i].innerHTML.slice(0, 9);
}
CodePudding user response:
Try:
let text = document.getElementsByClassName('demo');
for (let i=0; i < text.length; i ) {
text[i].innerHTML = text[i].innerHTML.slice(0, 9);
}
CodePudding user response:
You were iterating over an HTMLCollection
without referencing the index: text[i]
.
Modern JS tends to favour
querySelectorAll
for element selection, and usingforEach
to iterate over the elements.You should be targeting the
textContent
or theinnerText
of the element rather than itsinnerHTML
.Instead of
slice
I'd probably prefersubstr
to get characters from a string.
// Cache all the demo elements
const els = document.querySelectorAll('.demo');
// Loop over them, and update the textContent
els.forEach(el => {
let text = el.textContent;
el.textContent = text.substr(0, 9);
});
<p class="demo">The quick brown fox jumps over the lazy dog</p>
<p>The quick brown fox jumps over the lazy dog</p>
<p class="demo">The quick brown fox jumps over the lazy dog</p>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>