Bold clicked element, unbold the rest

JavaScript and client side scripting.

Moderator: General Moderators

Post Reply
Trahb
Forum Commoner
Posts: 36
Joined: Sat Jan 30, 2010 9:09 pm

Bold clicked element, unbold the rest

Post by Trahb »

Well, basically what I want to do is have a list of information. When the user clicks one thing, it goes bold. When they click another, it goes bold and the other goes back to normal.

The problem is, I've tried at least 10 different ways of this and none work.. Any ideas?

Right now i'm using

Code: Select all

onclick="document.getElementById('name').className='normal'; this.className='bold';"
But, since there are multiple elements with the id "name" it only takes the first one. How can i fix this? I feel like it's really simple (guarantee it is) i just can't figure it out..
User avatar
superdezign
DevNet Master
Posts: 4135
Joined: Sat Jan 20, 2007 11:06 pm

Re: Bold clicked element, unbold the rest

Post by superdezign »

An ID is supposed to be unique. Having more than one element with the same ID is improper markup and JavaScript is acting on the DOM as it should.
Trahb
Forum Commoner
Posts: 36
Joined: Sat Jan 30, 2010 9:09 pm

Re: Bold clicked element, unbold the rest

Post by Trahb »

I understand that, but would it really be ethical to have the same number of ids as there are entries for that particular user, and go through a loop of every number up to that amount each time they click a new entry? I feel like that's a waste, but, it may have to be what I do..
User avatar
superdezign
DevNet Master
Posts: 4135
Joined: Sat Jan 20, 2007 11:06 pm

Re: Bold clicked element, unbold the rest

Post by superdezign »

Ethical? Every record in a database has a unique ID. What's different about elements on your page?
One way to do this is to place all of the elements into an array and, upon clicking one, change them all.

Code: Select all

<ul>
  <li id="item-1" onclick="toggle('item-1')">Item #1</li>
  <li id="item-2" onclick="toggle('item-2')">Item #2</li>
  <li id="item-3" onclick="toggle('item-3')">Item #3</li>
</ul>

Code: Select all

var elements = ['item-1', 'item-2', 'item-3'];
function toggle(id) {
  for (var i in elements) document.getElementById(i).className = 'normal';
  document.getElementById(id).className = 'bold';
}
Post Reply