0

Homework problem, basically I need to code it to show only the selected attribute. I'm given several functions and expected to finish with only these. Textbook and internet examples are no help as they do not deal with this exact assignment.

Main thing is I am unsure how to setup an array that gets the for loop looking for the specified attribute. All the arrays I've seen deal with numbers, not boolean conditions.

Instructor will fail any assignment that doesn't use his functions.

"use strict";
var $ = function(id) { return document.getElementById(id); };

// the event handler for the click event of each h2 element
var toggle = function() {
    var h2 = this;                    // clicked h2 tag     
    var div = h2.nextElementSibling;  // h2 tag's sibling div tag
    var h2 = document.getElementById(this);

    // toggle plus and minus image in h2 elements by adding or removing a class
    if (h2.hasAttribute("class")) { 
        h2.removeAttribute("class");    
    } else { 
        h2.setAttribute("class", "minus"); 
    }
    // toggle div visibility by adding or removing a class
    if (div.hasAttribute("class")) { 
        div.removeAttribute("class");
    } else { 
        div.setAttribute("class", "open"); 
    } 
};

window.onload = function() {
    // get the h2 tags
    var faqs = $("faqs");
    var h2Elements = faqs.getElementsByTagName("h2");

    // attach event handler for each h2 tag     
    for (var i = 0; i < h2Elements.length; i++ ) {
        h2Elements[i].onclick = toggle;
    }
    // set focus on first h2 tag's <a> tag
    h2Elements[0].firstChild.focus();       
};

From teacher's Word document: "Add code to the toggle() function so only one answer can be displayed at a time. To do that, create an array of the h2 elements. Then, use a for loop to go through the h2 elements in the array and remove the class attribute for all h2 elements that aren’t the one that has been clicked. You also need to remove the class attributes for all of the div siblings of the h2 elements that weren’t clicked.

Mike
  • 1
  • 2
  • `var h2 = document.getElementById(this);` doesn't make sense, as `this` isn't a string at that point. – Pointy Apr 01 '19 at 16:26
  • Usually it's done like this: 1) reset (remove class from) everything, 2) set the class on the current element. This way there's no need to check any conditions. – georg Apr 01 '19 at 17:09

1 Answers1

-2

If you want to show the current time in JS, you can try to below code:

var today = new Date(); var date = today.getFullYear()+'-'+(today.getMonth()+1)+'-'+today.getDate(); var time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds(); var dateTime = date+' '+time;

DavidLin69
  • 1
  • 1
  • 6