Using WITH(...) in JavaScript

Michael Schwarz on Thursday, November 10, 2005

Some days ago I had a look in some Visual Basic source code and found the WITH statement there. I was thinking about how I can use this in JavaScript code. Below you will find a very simple script that allows you to use the With method (that will reduce your source code size of JavaScript files):

<html><body>

<style> .myclassname {font-family:arial;} </style>

<div id="test">My dummy text.</div>

<script type="text/javascript">

function With(o, p) { for(var prop in p) { o[prop] = p[prop]; } }

var ele = document.getElementById("test");

With(ele.style, { color:"red", fontSize:"12px", backgroundColor:"yellow" });

With(ele, { className:"myclassname" });

</script>

</body></html>