Quick Answers: Dynamically Apply a Border to all IMGs in the DOM

Many people have asked me to put up a Quick Answer that would allow them to dynamically apply a border to all IMG elements in the DOM.

Before …

border-002.png

After …

border-001.png

To dynamically apply CSS padding and borders to all IMG elements in the DOM, you can use the following Javascript function:

<html>
  <head>
    <script language="Javascript">
      function drawIMGBorder()
      {
        //Create a reference of all IMG elements in DOM
        var imgs = document.getElementsByTagName('img');

        //Loop through each of the IMG elements
        for(i = 0; i <= (imgs.length -1); i++)
        {
          //Apply CSS padding to current IMG
          imgs[i].style.padding = "2px";
          //Apply CSS border to current IMG
          imgs[i].style.border = "2px Solid #cacaca";
        }
      }
    </script>
  </head>
<body onLoad="drawIMGBorder();">
  <img src="picture1.jpg" border="0" />
  <img src="picture2.jpg" border="0" />
</body>
</html>

In this example the Javascript function is called when the page loads, but this can easily be modified to another Javascript event.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: