Home > Software engineering >  Add class to closest span if textarea not empty (for many textareas and elements)
Add class to closest span if textarea not empty (for many textareas and elements)

Time:11-15

I have 365 textareas per page. I need an indicator in which textarea there is text. Add class "noted-dot" to the closest span if the textarea is not empty.

I was only able to do this for the first textarea (see second script). But I need to do this for every textarea that has text in it. Textarea gets text in two ways: from localStorage (see first script); after user input.

var elements = document.getElementsByClassName('localstoragesave');
var elementsParent = document.querySelector("textarea").closest("span");

// Not this script. It save textarea value in localStorage
function checkValidity() {};
for (i=0; i<elements.length; i  ) {
 (function(element) {
   var id = element.getAttribute('id');
   element.value = localStorage.getItem(id   location.search);
   element.oninput = function() {
     localStorage.setItem(id   location.search, element.value);
     checkValidity();
   };
 })(elements[i]);
}

// This script
window.onload = function() {
    if(elements[0].value > "") {
        document.querySelector("textarea").closest("span").classList.add("noted-dot");
    }
};
<span >&ZeroWidthSpace;
    <div >
        <textarea  id="note-2022-10-28"></textarea>
    </div>
</span>

CodePudding user response:

Loop through all textarea elements and add the class conditionally.

for (i=0; i<elements.length; i  ) {
    if(elements[i].value != "") {
        elements[i].closest("span").classList.add("noted-dot");
    }
}

Fiddle -> https://jsfiddle.net/woce8pft/1/

Also if you want to add the doted-not class on input value change, add the conditions there too.

  • Related