2

I have a HTML file that has a modified style so that the underline tag results in a dotted line.

<style type="text/css">
  u {    
     border-bottom: 1px dashed #999;
     text-decoration: none;
  }
</style>

I want a function that will find elements by class and apply this underline style. It needs to be in a JS function because the underlining only occurs during certain events (mouseover and onclick). What would my javascript code look like?

So far I have:

    function underline(id){
    var elements = document.getElementsByClassName(id);
    for(var i=0; i<elements.length; i++){
        elements[i].style.?????}
    }
parap
  • 1,844
  • 5
  • 19
  • 28

3 Answers3

4

You can use this:

element.style.borderBottom = '2px dotted black';

See example

If you want to have the width of the "underline" match the width of the text, you can add this:

element.style.display = 'inline';
animuson
  • 53,861
  • 28
  • 137
  • 147
Braden Best
  • 8,830
  • 3
  • 31
  • 43
  • So I wouldn't even need a style change in my header with this? – parap Mar 06 '13 at 20:18
  • @jcoat No you would not. The javascript method for making an "underline" would be to use `element.style.borderBottom`, this creates a border on the bottom, achieving the effect you wanted. You can additionally set `element.style.display` to `"inline"` and have the width of the underline match the element's text. I've also updated the example to show it works with multiple elements :) – Braden Best Mar 06 '13 at 20:21
1

Why does it need to be done via javascript? You can just use the css class selector:

.myClass
{
  border-bottom: 1px dashed #999;
  text-decoration: none;
}
basher
  • 2,381
  • 1
  • 23
  • 34
  • I only want the class underlined on certain events – parap Mar 06 '13 at 20:19
  • 1
    @jcoat You can add the class to your particular elements during those events. It's still better to separate the styling from JavaScript and keep it in the CSS file. – Amy Mar 06 '13 at 20:21
  • As @sweetamylase said, just [add/remove](http://stackoverflow.com/questions/195951/change-an-elements-css-class-with-javascript) the classes during the event. – basher Mar 06 '13 at 20:32
1

Fyi, the <u> tag is non-semantic. Also, your css selector would be more useful if you use class for applying the styles:

.underline{
    border-bottom: 1px dashed #999;
    text-decoration: none;
}

So your html could be:

<p>Blah blah <span class="underline">underline this</span> blah blah.</p>
Amy
  • 7,388
  • 2
  • 20
  • 31