-1

Currently I am using CSS, HTML, and Javascript to work on creating functional tabs for a website as an example, and I am using getElementById to call for specific ids. Now, however, I want to add multiple items, including images, more text, titles, etc. under a single tab. How do I use getElementByClassName or getElementByClass (which should I use?) to group all the multiple items into a class and put it in Javascript?

I want to change the id into classes and add multiple elements (which I know how to):

<body>

    <p id="home">HOME TEXT!!!</p>

    /*Like:

    <div class="home">

         <h3>HOME TITLE!</h3>
         <img src="example.jpg">
         <p>Welcome to the home page!</p>

     </div>  

     */


    <p id ="about">ABOUT TEXT!!!</p>

    <script>

I don't know how to change this part (getElementById) to work on classes instead:

        function HomeTabFunction() {
            document.getElementById("home").style.display="block" 
            document.getElementById("homeTab").style.background = rgb(235, 197, 191)
            document.getElementById("about").style.display="none"
            document.getElementById("aboutTab").style.background = "lightblue"

        }

        function AboutTabFunction() {

            document.getElementById("about").style.display="block"
            document.getElementById("aboutTab").style.background = "blue"
            document.getElementById("home").style.display="none" 
            document.getElementById("homeTab").style.background = "lightblue"
        }

    </script>

    <h1>Little Shop </h1>
    <ul id="tabs">
        <li><a id="homeTab" href="javascript:void;" onclick="HomeTabFunction()">Home</a></li>
        <li><a id="aboutTab" href="javascript:void;" onclick="AboutTabFunction()">About</a></li>

</body>
Mykola
  • 3,343
  • 6
  • 23
  • 39
Grace
  • 45
  • 7
  • 1
    Have you considered to rely solely on css with class selectors or to use jquery ( which allows for css style selectors to gather arrays of dom elements and lets you operate on them ) ? – collapsar Nov 21 '15 at 19:28
  • why you are not using jquery. It will be very easy to handel. But for learning purpose you can go for document.getElementsByClassName. Here you can get getting element refferances: http://www.dyn-web.com/javascript/element-references/ – Dinesh Patra Nov 21 '15 at 19:31
  • @DineshPatra: Why *would* he use jQuery? It's already very easy to handle. –  Nov 21 '15 at 19:43
  • @collapsar: You don't need jQuery to use CSS style selectors in JS. jQuery simply uses the built in `.querySelectorAll()` method in browsers that support it (which is pretty much all browsers these days). –  Nov 21 '15 at 19:46
  • @squint Technically you are right. However, jquery complements the css selector set with their own which often come handy and lead to more maintainable code. However, these jquery-specific selectors canot take advantage from the highy optimized native implementation of `querySelectorAll` which might be an issue wrt application performance. – collapsar Nov 21 '15 at 20:04
  • @collapsar: I don't know why it would be more maintainable. They're just filters. If you use filter functions, you can easily tweak the code to suit a need if it changes. Overall, with the state of standards conformance, a person can easily get by with a handful of helper methods and have code as terse as jQuery, much faster, more memory efficient and less leaky. –  Nov 21 '15 at 20:40
  • @squint How would I emulate e.g. jquery's `:not` selector ? – collapsar Nov 21 '15 at 20:47
  • @collapsar: You mean their non-standard behavior of `:not()`? Filter it using a negated `elem.matches(selector)` –  Nov 21 '15 at 20:56
  • @squint: Ok, Applying that to sets of elements, combining a negated filter with other filters would be the task of the helper functions you mentioned ? – collapsar Nov 21 '15 at 21:09
  • @collapsar: Could be. There are many ways to go about it. Ultimately the native API handles most needs, and whatever it doesn't handle can be handled easily and cleanly. I just don't see much point to large abstractions any more. –  Nov 21 '15 at 21:18

5 Answers5

1

First of all its getElementsByClassName not getElementByClassName there is a S in end of element. Its plural because its returns more than one data. It returns array of of elements targeted by a class name.

You have to use for loop to work with getElementsByClassName

var classElem = document.getElementsByClassName
for(i=0;i < classElem.length;i++){
    if(classElem[i].innerHTML == "home"){
        classElem[i].style.display = "block"
        classElem[i].style.background = " rgb(235, 197, 191)"
        break;
    }
}

.innerHTML returns content of a tag <div>This text is innerHTML</div>

Skyyy
  • 1,539
  • 2
  • 23
  • 60
  • I see that the most common way people do is like what you showed here - creating variables and having them represent document.getElementsByClassName or document.getElementById, or something like that, and using the variable and '.innerHTML'. I don't know what the '.innerHTML' does. Is there is a way without using variables? (instead typing document.getElementsByClassName directly like my code above?) Thanks for your answer, though! – Grace Nov 22 '15 at 00:52
  • `document.getElementsByClassName` is used with the loop most the time so you don't have to write 1000 times if you have 1000 classes. i have update question with another example. Why don't you wanna use variable? – Skyyy Nov 22 '15 at 01:07
0

It's called getElementsByClassName and returns a HTMLCollection which you must iterate.

So replace

document.getElementById("id").whatever.foo = bar;

with

[].forEach.call(document.getElementsByClassName("class"), function(el) {
  el.whatever.foo = bar;
});
Oriol
  • 274,082
  • 63
  • 437
  • 513
0

To get the elements by their class name you use

...(name){

  document.getElementsByClassName(name);

}

but it returns an array, so you should iterate over each element returned.

0

First of all, getElementById() locates a single element on a page with the given unique ID.

getElementsByTagName() and getElementsByClassName() on the other hand return an array of elements whose tag/class match the given tag/class, respectively. Therefore, these are not simply interchangeable.

Why don't you try to generalize this so it works for N-tabs? With your current approach, you need to duplicate your code each time you add a new tab.

Example:

<!-- These do not need to be paragraphs.  Any element will work as long as it has this class and a unique ID -->
<p class="tab-text" id="home">HOME TEXT!!!</p>
<p class="tab-text" id ="about">ABOUT TEXT!!!</p>

        <h1>Little Shop </h1>

        <ul id="tabs">
            <li><a href="#home">Home</a></li>
            <li><a href="#about">About</a></li>
        </ul>

<script>
// Run when document is ready
(function() {
    // Find the UL parent of the tab links
    var tabs = document.getElementById('tabs');
    // Find all links inside it
    var tabLinks = tabs.getElementsByTagName('a');

    // Iterate through them and give them a click event handler
    for (var i = 0; i < tabLinks.length; i++)
    {
        tabLinks[i].onclick = function() {
            // Iterate over all the elements with a class of tab-text and hide them initially
            [].forEach.call(document.getElementsByClassName("tab-text"), function(el) {
              el.style.display = 'none';
            });

            // Then find the element whose ID matches the href attribute of the link clicked and show that
            document.getElementById(this.href.split('#')[1]).style.display = 'block';

            return false;
        }
    }
})();
</script>

The only thing you need to do if you want to add a new tab is to create a new element with a class of "tab-text" and any id attribute. Then add a new link inside the UL with a href attribute that points to the ID.

Working sample:

http://jsfiddle.net/h1cpsudL/

HaukurHaf
  • 13,522
  • 5
  • 44
  • 59
-1

Create some CSS styles.

If you want to add a style to an element, using javascript, try this :

var el = document.getElementById('theID');
el.className += 'newClassNameToAdd';

With JQuery...

$('#theID').addClass('newClassNameToAdd');

Now, if you have a HTMLCollection (multiple elements), using tags or class selectors :

var els = document.getElementsByTagName('tagName');
var len = els.length;

for (var i = 0; i < len; i++) {
    els[i].className += 'newClassNameToAdd';
}

With JQuery...

$('tagName').addClass('newClassNameToAdd');
Arpp
  • 301
  • 1
  • 11