Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
546 views
in Technique[技术] by (71.8m points)

character - Get all chars from strings of a CSS class with Vanilla Javascript

I wrote some code which extract the count from all chars of the strings in a class.

Is there a simple way with Vanilla JavaScript to get alle Characters of the strings without call every element of the class?

let allNews = "";
    allNews = allNews + document.getElementsByClassName("news-link")[0].innerHTML;
    allNews = allNews + document.getElementsByClassName("news-link")[1].innerHTML;
    allNews = allNews + document.getElementsByClassName("news-link")[2].innerHTML;
    allNews = allNews + document.getElementsByClassName("news-link")[3].innerHTML;
    allNews = allNews + document.getElementsByClassName("news-link")[4].innerHTML;
    allNews = allNews + document.getElementsByClassName("news-link")[5].innerHTML;
    allNews = allNews + document.getElementsByClassName("news-link")[6].innerHTML;
const allChars = allNews.length;
console.log(allChars)
<div class="ticker">
    <div class="news">
        <span><a href="#" class="news-link">OTHER NEWS</a></span>
        <span><a href="#" class="news-link">OTHER NEWS</a></span>
        <span><a href="#" class="news-link">OTHER NEWS</a></span>
        <span><a href="#" class="news-link">OTHER NEWS</a></span>
        <span><a href="#" class="news-link">OTHER NEWS</a></span>
        <span><a href="#" class="news-link">OTHER NEWS</a></span>
        <span><a href="#" class="news-link">OTHER NEWS</a></span>
    </div>
</div>
question from:https://stackoverflow.com/questions/66066532/get-all-chars-from-strings-of-a-css-class-with-vanilla-javascript

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Yes: Use a loop, and count the thing you actually want (allChars). That also has the advantage of being more robust -- it'll work with fewer rows, or more rows.

const elements = document.getElementsByClassName("news-link");
let allChars = 0;
for (const {innerHTML} of Array.from(elements)) {
    allChars += innerHTML.length;
}
console.log(allChars)
<div class="ticker">
    <div class="news">
        <span><a href="#" class="news-link">OTHER NEWS</a></span>
        <span><a href="#" class="news-link">OTHER NEWS</a></span>
        <span><a href="#" class="news-link">OTHER NEWS</a></span>
        <span><a href="#" class="news-link">OTHER NEWS</a></span>
        <span><a href="#" class="news-link">OTHER NEWS</a></span>
        <span><a href="#" class="news-link">OTHER NEWS</a></span>
        <span><a href="#" class="news-link">OTHER NEWS</a></span>
    </div>
</div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...