Javascript only affects one element

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

Answers:

Answer

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%;
}
?
Answer

"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; }

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.