How to assign a class or ID to a table within a JavaScript function?


Tags: javascript,html,mysql,css,json

Problem :

I have to use HTML, CSS and JavaScript (so no jQuery).

I have created a table that receives JSON data via API. I have a function to show/hide each of the table rows by clicking a check box. I already included the JavaScript function, but I cannot figure out where to place a class or id, so I can connect the function to each of the table rows. Generally, I would add a class to <td> for example, like this: <td class="example"> but in this case it won't work. The code breaks when I do this.

I did search online for hours, but wasn't able to find an answer. I'm not looking for finished code, but rather a hint/help how to achieve this.

This table is created using:

body {
    background: white;
}

h1 {
    color: black;
    font-size: 35px;
    text-align: center;
    font-family: 'Quicksand', sans-serif;
}

h2 {
    font-family: 'Quicksand', sans-serif;
    margin-left: 3.3em;
}

table, th , td {
    border: none;
    border-collapse: collapse;
    padding: 15px; 
    margin-left: 5em;
    margin-top: -25em;
}


table tr:nth-child(odd) {
    background-color: #f1f1f1;
}
table tr:nth-child(even) {
    background-color: #ffffff;
}
  
#form {
    font-family: 'Quicksand', sans-serif;
    margin-left: 5em;
}

#googleMap {
    margin-left: 45em;;
    margin-right: auto;
}

#chkbox_display {
    margin-left: 5em;
    margin-top: 3em;
    font-family: 'Quicksand', sans-serif;
}

.hidden {
    display: none;
}
<html>
<head>
<link rel="stylesheet" type="text/css" href="main.css"> 
<link href='https://fonts.googleapis.com/css?family=Quicksand' rel='stylesheet' type='text/css'>
    
<title>Weather App</title>    
</head>
    
    
<body>
<h1>Weather Forecast</h1>
<div id="id01"></div>    

<h2>Please enter the following information:</h2>    
<form id="form" onsubmit ="return fetchUrl()">
    Enter your City:<br>
    <input id="weather_city" placeholder="Entere here..."><br>
    How to display values: <br>
    <select id="weather_scale">
        <option value="Metric">Metric Units (Celcius/mm)</option>
        <option value="Imperial">Imperial Units (Fahrenheit/inch)</option>
    </select><br>
    Number of days to show weather:<br>
    <select id="weather_numberOfDays">
        <option value="1">Today only</option>
        <option value="2">2 days</option>
        <option value="3">3 days</option>
        <option value="4">4 days</option>
        <option value="5">5 days</option>
    </select>
    <br><br>
    <button onclick="initialize">Submit</button>
        </form>


<div id="chkbox_display">
<form action="#">
    <input type="checkbox" name="chkbox" id="chkbox"/>
    <label for="chkbox">Max. Temp.</label>
    
    <input type="checkbox" name="chkbox" id="chkbox"/>
    <label for="chkbox">Min. Temp</label>
    
    <input type="checkbox" name="chkbox" id="chkbox"/>
    <label for="chkbox">Rainfall</label>
    
    <input type="checkbox" name="chkbox" id="chkbox"/>
    <label for="chkbox">Pressure</label>
    
    <input type="checkbox" name="chkbox" id="chkbox"/>
    <label for="chkbox">Humidity</label>
    
    <input type="checkbox" name="chkbox" id="chkbox"/>
    <label for="chkbox">Wind Speed</label>
    </form>  
</div>
    
<script>
    
function initAutocomplete() {

    weather_city = new google.maps.places.Autocomplete(
    (document.getElementById('weather_city')),
    {types: ['geocode']});
    weather_city.addListener('place_changed');
}
        
    </script>    
    
<script src="http://maps.googleapis.com/maps/api/js?key=AIzaSyDgIpTEmegx81sL3ukhIdYVQrPkufyjEj4&callback=initalize&libraries=places&callback=initAutocomplete"></script>

<script>
    
    var longitude;
    var latitude;
    
function initalize(arr) {    
    var lon = arr.city.coord.lon;
    var lat = arr.city.coord.lat;
    
    var mapProp = {
    center:new google.maps.LatLng(lat,lon),
    zoom:10,
    mapTypeId:google.maps.MapTypeId.ROADMAP
  }
  var map=new google.maps.Map(document.getElementById("googleMap"), mapProp);
}
    
</script>


<div id="googleMap" style="width:600px;height:480px;"></div>
 

<section>
    <div id="table"> 
<!--
    <tr>
        <td class="hidden">example</td>
        <td class="hidden"></td>
        <td class="hidden"></td>
    </tr>    
-->
    
    </div>
    </section>   
    
<script> 
    
function getJson(request) {
    
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.open("GET", request, true);
    xmlhttp.send();
    xmlhttp.onreadystatechange=function() {
        if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        myFunction(xmlhttp.responseText);  
    }
}
}

function fetchUrl() {
    var form = document.getElementById("form");
    var city = form.weather_city.value;
    var value = form.weather_scale.value;
    var days = form.weather_numberOfDays.value;
    
    var url = "http://api.openweathermap.org/data/2.5/forecast/daily?q="+city+"&type=accurate,us&mode=json&appid=a0dd3d46dd5b22c0581030acf10af408&units="+value+"&cnt="+days;
    
    getJson(url);
    return false;
}
    
function myFunction(response) {
    var arr = JSON.parse(response);
    initalize(arr);
    var i;
    var out = "<table>";

    for(i = 0; i < arr.list.length; i++) {
        out += "<tr><td>" +
        new Date(arr.list[i].dt * 1000) +
        "</td></tr>" +
        "<tr><td>" +
        getIcon(arr.list[i].weather[0].icon) +
        "</td><td>" +
        arr.list[i].weather[0].description +
        "</td><tr>" +
        "</tr><td>" +
        "Min. Temperature" +
        "</td><td>" +
        arr.list[i].temp.min +
        "</td><tr>" +
        "</tr><td>" +
        "Max. Temperature" +
        "</td><td>" +
        arr.list[i].temp.max +
        "</td><tr>" +
        "</tr><td>" +
        "Pressure" +
        "</td><td>" +
        arr.list[i].pressure +
        "</td><tr>" +
        "</tr><td>" + 
        "Windspeed" +
        "</td><td>" +
        arr.list[i].speed +
        "</td><tr>" +
        "</tr><td>" + 
        "Humidity" +
        "</td><td>" +
        arr.list[i].humidity +
        "</td><tr>" +
        "</tr><td>" +   
        "Predicted Rainfall" +
        "</td><td>" +
        arr.list[i].rain +
        "</td><td>";
    }
    out += "</table>";
    document.getElementById("table").innerHTML = out;
}
    
function getIcon(s) {
    return("<img src=\"http://openweathermap.org/img/w/"+s+".png\"/>");
}
    
</script>   
    
<script>
    //function to show and hide pressure, humidity, etc.... doesnt work yet. not connected!
    function showHide() {
        var checkbox = document.getElementById("chkbox");
        var hiddenInput = document.getElementsByClassName("hidden");
        
        for(var i = 0; i !=hiddenInput.length; i++) {
            if(checkbox.checked) {
                hiddenInput[i].style.display = "inline";
            } else {
                hiddenInput[i].style.display = "none";
            }
            }
        }
    </script>

</body>
</html>



Solution :

The simplest means of achieving this, given the current approach, is to convert the HTML of the <td> opening tags from:

"<tr><td>"

to:

"<tr><td class='example'>"

And then use CSS to style the relevant elements, for example:

.example {
  color: #f90;
}

Or, once you've assigned the string of innerHTML, you could simply add this line:

// retrieves the collection of <td> elements from within the
// element with the id of 'table', and uses Array.from() to
// convert that collection into an Array.
// Then iterates over the array of elements using
// Array.prototype.forEach():
Array.from( document.querySelectorAll('#table td') ).forEach(function (td) {
  // within the anonymous function the 'td' argument is a reference
  // to the current array-element of the array over which we're
  // iterating.

  // here we use the Element.classList API to add the 'example'
  // class-name to the existing (if any) class-names of the <td>
  // elements:
  td.classList.add('example');
});

body {
    background: white;
}

h1 {
    color: black;
    font-size: 35px;
    text-align: center;
    font-family: 'Quicksand', sans-serif;
}

h2 {
    font-family: 'Quicksand', sans-serif;
    margin-left: 3.3em;
}

table, th , td {
    border: none;
    border-collapse: collapse;
    padding: 15px; 
    margin-left: 5em;
    margin-top: -25em;
}


table tr:nth-child(odd) {
    background-color: #f1f1f1;
}
table tr:nth-child(even) {
    background-color: #ffffff;
}
  
#form {
    font-family: 'Quicksand', sans-serif;
    margin-left: 5em;
}

#googleMap {
    margin-left: 45em;;
    margin-right: auto;
}

#chkbox_display {
    margin-left: 5em;
    margin-top: 3em;
    font-family: 'Quicksand', sans-serif;
}

.hidden {
    display: none;
}

.example {
  color: #f90;
}
<html>
<head>
<link rel="stylesheet" type="text/css" href="main.css"> 
<link href='https://fonts.googleapis.com/css?family=Quicksand' rel='stylesheet' type='text/css'>
    
<title>Weather App</title>    
</head>
    
    
<body>
<h1>Weather Forecast</h1>
<div id="id01"></div>    

<h2>Please enter the following information:</h2>    
<form id="form" onsubmit ="return fetchUrl()">
    Enter your City:<br>
    <input id="weather_city" placeholder="Entere here..."><br>
    How to display values: <br>
    <select id="weather_scale">
        <option value="Metric">Metric Units (Celcius/mm)</option>
        <option value="Imperial">Imperial Units (Fahrenheit/inch)</option>
    </select><br>
    Number of days to show weather:<br>
    <select id="weather_numberOfDays">
        <option value="1">Today only</option>
        <option value="2">2 days</option>
        <option value="3">3 days</option>
        <option value="4">4 days</option>
        <option value="5">5 days</option>
    </select>
    <br><br>
    <button onclick="initialize">Submit</button>
        </form>


<div id="chkbox_display">
<form action="#">
    <input type="checkbox" name="chkbox" id="chkbox"/>
    <label for="chkbox">Max. Temp.</label>
    
    <input type="checkbox" name="chkbox" id="chkbox"/>
    <label for="chkbox">Min. Temp</label>
    
    <input type="checkbox" name="chkbox" id="chkbox"/>
    <label for="chkbox">Rainfall</label>
    
    <input type="checkbox" name="chkbox" id="chkbox"/>
    <label for="chkbox">Pressure</label>
    
    <input type="checkbox" name="chkbox" id="chkbox"/>
    <label for="chkbox">Humidity</label>
    
    <input type="checkbox" name="chkbox" id="chkbox"/>
    <label for="chkbox">Wind Speed</label>
    </form>  
</div>
    
<script>
    
function initAutocomplete() {

    weather_city = new google.maps.places.Autocomplete(
    (document.getElementById('weather_city')),
    {types: ['geocode']});
    weather_city.addListener('place_changed');
}
        
    </script>    
    
<script src="http://maps.googleapis.com/maps/api/js?key=AIzaSyDgIpTEmegx81sL3ukhIdYVQrPkufyjEj4&callback=initalize&libraries=places&callback=initAutocomplete"></script>

<script>
    
    var longitude;
    var latitude;
    
function initalize(arr) {    
    var lon = arr.city.coord.lon;
    var lat = arr.city.coord.lat;
    
    var mapProp = {
    center:new google.maps.LatLng(lat,lon),
    zoom:10,
    mapTypeId:google.maps.MapTypeId.ROADMAP
  }
  var map=new google.maps.Map(document.getElementById("googleMap"), mapProp);
}
    
</script>


<div id="googleMap" style="width:600px;height:480px;"></div>
 

<section>
    <div id="table"> 
<!--
    <tr>
        <td class="hidden">example</td>
        <td class="hidden"></td>
        <td class="hidden"></td>
    </tr>    
-->
    
    </div>
    </section>   
    
<script> 
    
function getJson(request) {
    
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.open("GET", request, true);
    xmlhttp.send();
    xmlhttp.onreadystatechange=function() {
        if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        myFunction(xmlhttp.responseText);  
    }
}
}

function fetchUrl() {
    var form = document.getElementById("form");
    var city = form.weather_city.value;
    var value = form.weather_scale.value;
    var days = form.weather_numberOfDays.value;
    
    var url = "http://api.openweathermap.org/data/2.5/forecast/daily?q="+city+"&type=accurate,us&mode=json&appid=a0dd3d46dd5b22c0581030acf10af408&units="+value+"&cnt="+days;
    
    getJson(url);
    return false;
}
    
function myFunction(response) {
    var arr = JSON.parse(response);
    initalize(arr);
    var i;
    var out = "<table>";

    for(i = 0; i < arr.list.length; i++) {
        out += "<tr><td>" +
        new Date(arr.list[i].dt * 1000) +
        "</td></tr>" +
        "<tr><td>" +
        getIcon(arr.list[i].weather[0].icon) +
        "</td><td>" +
        arr.list[i].weather[0].description +
        "</td><tr>" +
        "</tr><td>" +
        "Min. Temperature" +
        "</td><td>" +
        arr.list[i].temp.min +
        "</td><tr>" +
        "</tr><td>" +
        "Max. Temperature" +
        "</td><td>" +
        arr.list[i].temp.max +
        "</td><tr>" +
        "</tr><td>" +
        "Pressure" +
        "</td><td>" +
        arr.list[i].pressure +
        "</td><tr>" +
        "</tr><td>" + 
        "Windspeed" +
        "</td><td>" +
        arr.list[i].speed +
        "</td><tr>" +
        "</tr><td>" + 
        "Humidity" +
        "</td><td>" +
        arr.list[i].humidity +
        "</td><tr>" +
        "</tr><td>" +   
        "Predicted Rainfall" +
        "</td><td>" +
        arr.list[i].rain +
        "</td><td>";
    }
    out += "</table>";
    document.getElementById("table").innerHTML = out;
  
  Array.from( document.querySelectorAll('#table td') ).forEach(function (td) {
    td.classList.add('example');
  });
}
    
function getIcon(s) {
    return("<img src=\"http://openweathermap.org/img/w/"+s+".png\"/>");
}
    
</script>   
    
<script>
    //function to show and hide pressure, humidity, etc.... doesnt work yet. not connected!
    function showHide() {
        var checkbox = document.getElementById("chkbox");
        var hiddenInput = document.getElementsByClassName("hidden");
        
        for(var i = 0; i !=hiddenInput.length; i++) {
            if(checkbox.checked) {
                hiddenInput[i].style.display = "inline";
            } else {
                hiddenInput[i].style.display = "none";
            }
            }
        }
    </script>

</body>
</html>

This does, of course, assume that you're correct that you need to append class-names to the elements; with no explanation of the problem you're trying to solve by adding the class-names it's hard to offer better advice.


    CSS Howto..

    How do I move the search bar to the top without hiding it? [closed]

    How to make transition effect on css sprite hover

    How to make a unique line thinner using NVD3

    How to add a new CSS class to a Link Badge if the value is 0?

    How to make div scroll down with a page once it reaches top of page?

    Using CSS, how do I change the font color of parent
  • tag if child
  • tag is hovered over
  • How to do :hover on circle navigation from angle x to y

    How can I avoid a “Flash of Unstyled Content” using fixed-width cells in CSS Tables?

    How can I position two divs on the same line and have them act responsive?

    CSS: how to make label appear right of the radio?

    How can I resize these divs while keeping the same layout?

    How to improve page loading which includes css and jquery files

    How to fix
      's in footer that break in ie8 & ie9, but is perfect in ie7, FF, Safari & Chrome

    How to disable Bootstrap 3 collapse nav menu css

    How should I divide up CSS files to support multiple devices?

    How to to change CSS double class properties through script

    How to put bull inside css circle

    CSS selectors: how to make element hovering change wrapper's style

    How to simplify cross-browsing css animation keyframe?

    How can I make a fix positioned menu bar?

    CSS - How to make a div as wide as a containing child img

    How to stop the latter part of javascript from being called?

    How to completely gray out an image with css?

    how to get the css floating property to work with four divs?

    Shows a dropdown element with jQuery

    How to add and remove div's (input)

    Does anybody know how I can adjust this CSS to achieve the desired hyperlink effect I'd like?

    How to ensure three DIV are the same height regardless of content

    Hide all div element but show first two

    How to Stop jQuery from Buffering Hover Effects?