DOM Node Properties and Attributes

by Deepak Anand

HTML

<input id ="textfield" type = "text" value = "foo" readonly>
    
    <div>
    <button id = "getAttrBtn"> Print Attribute </button>
    <span id ="attrValue"></span>
    <button id = "setAttrBtn"> Change Attribute to bar </button>
    </div>
    <div>
    <button id = "getDomPropBtn"> Print Dom Property </button>
    <span id ="domPropValue"></span>
    <button id = "setDomPropBtn"> Change Property to baz </button>
    </div>
    <br />
    <div> Now click on this button to <button id ="removeReadOnlyBtn"> make text-field editable </button>  and update the value interactively i.e. by typing. Subsequent setting via setAttribute will not work anymore, where as updates/queries via the DOM object works always</div>

CSS

body{
    font-family: monospace;
    
}

JavaScript

(function(){
    
    // alias lengthy DOM API
    // http://stackoverflow.com/questions/1007340/javascript-function-aliasing-doesnt-seem-to-work
    var elemId = document.getElementById.bind(document);
    
    var textInput = elemId("textfield");
    
    var getAttrBtn = elemId("getAttrBtn");
    
    getAttrBtn.addEventListener("click", function(){        
        elemId("attrValue").textContent = textInput.getAttribute("value");
    });    
    
    var setAttrBtn = elemId("setAttrBtn");    
    setAttrBtn.addEventListener("click", function(){        
       textInput.setAttribute("value", "bar");
    });
    
    var getDomPropBtn = elemId("getDomPropBtn");
    getDomPropBtn.addEventListener("click", function(){
        
        elemId("domPropValue").textContent = textInput.value;
    });
    
    var setDomPropBtn = elemId("setDomPropBtn");    
    setDomPropBtn.addEventListener("click", function(){        
       textInput.value = "baz";
    });
    
   var removeReadOnlyBtn = elemId("removeReadOnlyBtn");
    removeReadOnlyBtn.addEventListener("click", function(){
        
        textInput.removeAttribute("readonly");
    }); 
    
    
})();