Change getElementById to work with getElementByClass
New here? Learn about Bountify and follow @bountify to get notified of new bounties! x

In the linked pen, I'm highlighting a specific character count range of the contents of an element with id="characters". Since the javascript is using getElementById, I can only have the character count applied to the first element with the ID.

I want the character count applied to an unlimited number of elements on the page. I'm assuming getElementByClass would let me apply it to any number of elements by simply applying a Class instead of an ID.

I'm looking for someone to rewrite the code using Vanilla Javascript so I can apply the character count highlight to any number of elements, preferably via a Class instead of an Id.

There will be a bonus tip of $5.00 if you add a toggle button that turns the highlight on/off.

I wanted to say, that ID is unique, so you can make it only once. And regarding the solution, it's static, since applied to a range (45, 75). To work dynamically, just surround the text with highlight class in span, and conserve the toggler, he will do it right. Similar actions are easy with jquery, think about it.
Chlegou almost 4 years ago

Crowdsource coding tasks.

1 Solution


<p class="characters">Is not the best k...
<p class="characters">Is not the best k...


(function() {
    var eles = document.getElementsByClassName("characters");
    for (var i = 0; i < eles.length; i++) {

function highlight(ele) {
    var str= ele.innerHTML;
    var str1 = "";
    for(var i = 45; i < 75; i++) {
        str1 += str[i];
    var n=str.replace(str1,'<span class="highlight">' + str1 + '</span>');

For highlighting:


.highlight-off .highlight {
    background-color: transparent;


function togglehighlight() {
    if (!document.body.classList.contains('highlight-off'))
// ...
document.getElementById("toggle").addEventListener("click", togglehighlight);