Search code examples
javascripthtmlautocompletespell-checking

Disable spellcheck and autocomplete globally in a HTML document?


It's possible to disable spellcheck or autocomplete on individual input elements by adding the tags spellcheck="false" or autocomplete="off" to that element.

But for those who would like to disable it globally across the entire DOM, is there a way to do this using vanilla javascript or HMTL (accounting for the fact that new input elements may be created over the lifetime of the page)?


Solution

  • In vanilla javascript, one option would be to iterate all the inputs on the page and apply the necessary attribute, something like this:

    var inputs = document.getElementsByTagName("input");
    for(var i = 0; i < inputs.length; i++){
        inputs[i].setAttribute("spellcheck", "false");
    }
    

    For a more dynamic situation where you're unable to control the creation of new inputs, a mutation observer could be used to apply the desired attributes to dynamically created:

    window.addInput = function(){
      var container = document.getElementById("container");
      var input = document.createElement("input");
      input.setAttribute("type", "text");
      container.appendChild(input);
      container.appendChild(document.createElement("br"));
    }
    
    //MutationObserver docs: https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver
    var observer = new MutationObserver(function (e){
      for(var i = 0; i < e.length; i++){
        for(var j = 0; j < e[i].addedNodes.length; j++){
          if(["INPUT", "TEXTAREA"].indexOf(e[i].addedNodes[j].tagName) > -1){
            e[i].addedNodes[j].setAttribute("spellcheck", "false");
            console.log("attribute set")
          }
        }
      }
    }).observe(document.getElementById("container"), {childList:true});
    <button onclick="addInput();">
    Add Input
    </button>
    
    <div id="container">
    
    </div>