1

I don't understand, the border is only visible on the first item, why?

HTML

<div id="theContainer">
    <div id="item">Content 1</div>
    <div id="item">Content 2</div>
</div>​

JavaScript

document.getElementById('item').style.borderTop = '1px solid #0ea2c7';​

JsFiddle: here

LazyTarget
  • 879
  • 1
  • 14
  • 30
Hai Truong IT
  • 4,126
  • 13
  • 55
  • 102
  • 2
    `id` is supposed to be unique within the document. You may want to use class instead. – nhahtdh Dec 26 '12 at 05:13
  • Are you sure about javascript support borderTop method of css ? – Hkachhia Dec 26 '12 at 05:18
  • well, why don't you use this in a css property like this one http://jsfiddle.net/SbNKa/53/ ! no need of js! – Muhammad Talha Akbar Dec 26 '12 at 05:26
  • It's likely that there are better approaches to what you are trying to do than style elements explicitly using script. One obvious one is to define a class with the `border-top: 1px solid #0ea2c7` property and add that class to the elements. Better yet, make a CSS declaration such as `#theContainer.border-items .item { border-top: 1px solid #0ea2c7; }` and then you'll just need to add the `border-items` class to the single `#theContainer` element. –  Dec 26 '12 at 05:59
  • Hope this may work : [reference](http://stackoverflow.com/questions/3349332/getelementsbyclassname-not-working) – Surinder ツ Dec 26 '12 at 06:05

2 Answers2

2

You can use document.getElementsByClassName

JavaScript

var elements = document.getElementsByClassName('item');
for (i =0; i < ele.length; i++)    {
    elements[i].style.borderTop = '1px solid #000';
}

HTML

<div id="theContainer">
    <div class="item">Content 1</div>
    <div class="item">Content 2</div>
</div>​

CSS

#theContainer {
    height: 100px;
    width: 500px;
    position: relative;
    border: 1px solid #900;
    padding: 10px;
}
.item {
    height: 50px;
    width: 100%;
}
​
LazyTarget
  • 879
  • 1
  • 14
  • 30
Salil
  • 46,566
  • 21
  • 122
  • 156
-1

"document.getElementById" means "Returns a reference to the element by its ID", see here; and id means identity, you should have only one element in your dom tree per id.

If you want to style multiple elements, try to use class.

HTML

<div id="theContainer">
    <div class="item">Content 1</div>
    <div class="item">Content 2</div>
</div>

CSS

.item { border-top: 1px solid #0ea2c7; }
LazyTarget
  • 879
  • 1
  • 14
  • 30
Villa
  • 158
  • 6