0

Firstly, my apologies if the answer to my query is displayed elsewhere, or if my below explanation lacks any clarity/ correct terminology. I've searched, but my knowledge - and I used the word knowledge rather liberally! - of JS is such that I've been unable to collate answers and solve my issue.

I have multiple occurrences of 'MoreInfo' as a div id in the body of my html, however I know that as I've used .getElementById the Id needs to be unique and only the first occurrence will be actioned on click. I believe that changing to .getElementsByClassName may be the solution to enable me to have multiple occurrences of a class name opposed to being restricted to one instance of .getElementById but I'm unsure of how to amend the below to have it working, and my attempts have fallen flat.

I'm looking for a solution without using Jquery, or without needing to add additional ID's as I have done below by adding a "2", as I would need to do this a vast number of times and the number of times is undetermined.

Help would be much appreciated.

function showMore(el) {
el.style.display == "none";
document.getElementById('MoreInfo').style.display = '';
return false;
}

function showMore2(el) {
el.style.display == "none";
document.getElementById('MoreInfo2').style.display = '';
return false;
}
3
  • 2
    "my attempts have fallen flat" — We can't tell you what is wrong with your attempts to use getElementsByClassName unless you share them with us.
    – Quentin
    Feb 25, 2015 at 13:57
  • Why do you have el.style.display == "none"; as your first line? Did you mean el.style.display = "none";? The first one doesn't do anything (it checks if if the display is none and throws away the return value)
    – soktinpk
    Feb 25, 2015 at 13:57
  • @Quentin,Fair point! I have used trial and error (lots!) and as such couldn't state that which didn't work accurately. I'm not proficient with JS so would rather work again from a blank slate of peoples suggestions rather than wasting peoples times with that which I claim to be wrong/not to work when really it may be human error on my part :)
    – f484126
    Feb 25, 2015 at 14:05

2 Answers 2

1

You can use getElementsByClassName("MoreInfo") and iterate over the list once you've got it.

Using several ID's is a bad idea since ID's are unique and should not be used more than once by convention. If you want properties to be used multiple times, you should be using classes anyhow.

function showMore(el) {
    el.style.display == "none";
    var elements = document.getElementsByClassName("MoreInfo");
    for (i = 0; i < elements.length; i++) {
        elements[i].style.display = '';
    }
    return false;
}

The getElementsByClassName will return a list of all the elements in the DOM that have that class name. You should iterate over that list to do something to all of them within the for loop.

EDIT

Based on further information obtained from the comments, I think the best answer is to use class names not ID's as previously suggested. But additionally, it seems that you will want to find the associated child of the given link.

Due to the structure you have outlined in the JSFiddle this can be accomplished relatively easily, but you will want to take into consideration any additional nesting you may end up doing.

HTML

<div>
<span class="details"><a href="#" onClick="showMore(this)">Click For More Info</a></span>

<div class="MoreInfo" style="display:none;"><strong>More Info Shown Here</strong>
</div>

<div>
<span class="details"><a href="#" onClick="showMore(this)">Click For More Info Again</a></span>

<div class="MoreInfo" style="display:none;"><strong>Different     Information Shown Here</strong>
</div>

Javascript

function showMore(el) {
    el.style.display = "none";
    el.parentNode.parentNode.getElementsByClassName("MoreInfo")[0].style.display = 'block';
    return false;
}

The javascript function takes the current element, hides it (you have an extra = in there, I presume this was intended to hide the original link.

Then we take the grandparent of the element. The parent is the span, the parent of the span is a div. If we do a getElementsByClassName("MoreInfo") on the parent div then there will be only one item in there, which will be the one you want. As such, we reference the item at index [0] and set its display property.

This will work for all subsequent links that have the same structure:

<div>
  <span>
    <a link>
  </span>
  <div class="MoreInfo"></div>
</div>

JSFiddle to see the example.

4
  • Thank you for taking the time to read my question - if possible would can you please amend my code in line with what you have stated, as I don't understand what it is i need to do?
    – f484126
    Feb 25, 2015 at 14:02
  • @f484126 I have, although I don't understand what you are trying to accomplish with the showMore function so it is hard to say if it will work as-is
    – leigero
    Feb 25, 2015 at 14:10
  • @f484126 your fiddle doesn't have multiple classnames or ID's. How would you want it to work with multiples? Please show this in the fiddle.
    – leigero
    Feb 25, 2015 at 14:49
  • @f484126 I believe that edit should answer your question.
    – leigero
    Feb 25, 2015 at 15:48
-3

The "ID" must be unique, because of it "getElementById" is singular (Element), not plural like getElementsByTagName or getElementsByClassName (Elements).

But you can use getElementsByTagName, getElementsByClassName, xpath or another ways to look for a particular DOM node/s.

https://developer.mozilla.org/en/docs/Introduction_to_using_XPath_in_JavaScript

Edit 2a: Using xpath

It's obvious that if you use a single class for every block it's easiest to use getElementsByClassName. But with xpath you have more power to search into a document for a more complex pattern (a div tag with class "foo" and id that begins with "bar").

Example: http://jsfiddle.net/OscarGarcia/a8jqm636/1/

HTML code:

<ul>
    <li><a href="information1" onclick="return showMore(this)">
        Show information #1</a></li>
    <li><a href="information2" onclick="return showMore(this)">
        Show information #2</a></li>
    <li><a href="information3" onclick="return showMore(this)">
        Show information #3</a></li>
</ul>
<div id="information1" class="information">This is information text #1: This is interesting!<br /><img src="http://upload.wikimedia.org/wikipedia/commons/thumb/0/0f/Icon-OK.jpg/35px-Icon-OK.jpg" alt="OK"/></div>
<div id="information2" class="information">This is information text #2: What happened? Wow!<br /><img src="http://upload.wikimedia.org/wikipedia/commons/d/d5/Face-angel.svg" alt="angel" /></div>
<div id="information3" class="information">This is information text #3: Be happy with CSS!<br /><img src="http://upload.wikimedia.org/wikipedia/commons/thumb/9/92/Gnome-face-smile-big.svg/92px-Gnome-face-smile-big.svg.png" alt="happy" /></div>

CSS code:

.information {
    display: none;
}

JavaScript code:

function showMore(el) {
    var nodes = document.evaluate('//div[@class="information"]', document, null, XPathResult.ANY_TYPE, null);
    var result = nodes.iterateNext();
    var target = el.getAttribute("href");
    while (result) {
        if (result.getAttribute("id") == target) {
            result.style.display = 'block';
        } else {
            result.style.display = 'none';
        }
        result = nodes.iterateNext();
    }
    return false;
}

This code will look for every div tag with class "information" and compare its "id" with the content of "href" attribute of clicked link.

Hope it helps.

Edit 2b: Show/hide information blocks without javascript

Probably you don't need to use javascript at all! This is an example without javascript:

HTML code:

<ul>
    <li><a href="#information1">Show information #1</a></li>
    <li><a href="#information2">Show information #2</a></li>
    <li><a href="#information3">Show information #3</a></li>
</ul>
<div id="information1" class="information">
    This is information text #1: This is interesting!<br />
    <img src="http://upload.wikimedia.org/wikipedia/commons/thumb/0/0f/Icon-OK.jpg/35px-Icon-OK.jpg" alt="OK"/>
</div>
<div id="information2" class="information">
    This is information text #2: What happened? Wow!<br />
    <img src="http://upload.wikimedia.org/wikipedia/commons/d/d5/Face-angel.svg" alt="angel" />
</div>
<div id="information3" class="information">
    This is information text #3: Be happy with CSS!<br />
    <img src="http://upload.wikimedia.org/wikipedia/commons/thumb/9/92/Gnome-face-smile-big.svg/92px-Gnome-face-smile-big.svg.png" alt="happy" />
</div>

CSS code:

.information {
    display: none;
}

.information:target {
    display: block;
}

As you can see, all information blocks are hidden on page load. When you target every block its CSS selector changes to "target", so the block are shown and every other are hidden. When you target another block, again the rest are hidden and only selected is visible.

EDIT 1: Little error on variable assignment.

After reading deeptly I saw a little error with variable assignment:

function showMore(el) {
  el.style.display = "none";
  document.getElementById('MoreInfo').style.display = 'none'; // ¿none? ¿block?
  return false;
}

You mustn't use "==" to assign a value.

9
  • The question has already identified getElementsByClassName as a solution, it is asking how to use it.
    – Quentin
    Feb 25, 2015 at 14:06
  • Could you use jsfiddle.net and upload your code? Feb 25, 2015 at 14:10
  • @ Redstar The code i provided in my question works, however perhaps the double == isn't required.
    – f484126
    Feb 25, 2015 at 14:11
  • Sorry, I went to sleep for a while. What are you trying to do? Are you trying to hide all elements with this class? Show it? Please, more details are welcome! :) Feb 25, 2015 at 17:15
  • @f484126 here is my two cents. Hope it helps you :) there is an xpath example and a pure CSS example (without javascript). Have fun! Feb 25, 2015 at 19:29

Not the answer you're looking for? Browse other questions tagged or ask your own question.