...

View Full Version : multiple getelementbyid



cloudstryphe
05-24-2012, 10:17 PM
Hello. I have a page that is displaying facebook news feeds and I have multiple instances of the same id's and classes in the HTML for display. For each single feed from facebook, I would like to be able to click an "open" button and have a hidden div appear under it which displays comments and such. I know how to do this for 1 feed using javascript, but how do I do it for multiple feeds with the same id's?

The HTML looks something like this:


<div id="facebookfeed">
Facebook Feed Info
<a onclick="opencomment()">Open Comments</a>
</div>
<div id="facebookcomments">
facebookcomments
</div>


The I have the div "facebookcomments" as display: none;. When I have one single facebook feed, I can easily have the comment display and hide, but when I have multiple instances of the above html, the javascript only opens and closes the first comment box. How would I make the javascript work to open only each individual commentbox?

Here's my current basic javascript to open 1 commentdiv.



function opencomment() {
var divstyle = new String();
divstyle = document.getElementById("facebookcomments").style.display;
if(divstyle.toLowerCase()=="block" || divstyle == "")
{
document.getElementById("facebookcomments").style.display = "none";
}
else
{
document.getElementById("facebookcomments").style.display = "block";
}
}


Thank you in advance!

xelawho
05-24-2012, 10:31 PM
if you have multiple elements sharing the same ID that is illegal html and it will only confuse the javascript. To begin with you should investigate how you can append something to those IDs (usually a number but it doesn't have to be) to make them unique and thus easier to reference

cloudstryphe
05-24-2012, 10:39 PM
So you're saying change "facebookcomments" to "facebookcomments 1"? At that point I could just repeat the javascript code for each div, right?

felgall
05-24-2012, 10:42 PM
If you want to attach the same value to multiple tags you should use a class rather than an id. You can only have one instance of any single id in a web page but can have as many instances of a class as you like.

Using a class you can then simply reference each tag with that class numerically within the script itself.

cloudstryphe
05-24-2012, 10:46 PM
Ok, I'll change them to classes. When you say address them numerically, do you mean by adding a "1" at the end of each class in the html then referencing it that way in the javascript?

felgall
05-25-2012, 04:16 AM
Ok, I'll change them to classes. When you say address them numerically, do you mean by adding a "1" at the end of each class in the html then referencing it that way in the javascript?

No.

When you use getElementsByClassName() you get back a list of all the tags with that class. You can then set up a for loop to process through that list.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum