Problem Statement
Write JavaScript code hideOddRows.js that attaches to the button click event and hides the odd rows of the table when clicked.
Expected Output
When you click on "Hide Odd Rows":
Solution
/* hideOddRows.js */
document.querySelector('[name=HideRows]').onclick = hideRows;
function hideRows(){
var elements = document.getElementsByClassName('hide');
Array.prototype.forEach.call(elements, function(element){
element.style.display = "none";
});
return true;
}
<!DOCTYPE html>
<html>
<head>
<title>Hide odd rows</title>
<meta charset="UTF-8">
</head>
<body>
<div style="background-color:#8F9779;width:200px;height:30px;">
</div>
<hr style="width:200px" align="left">
<table border="1" >
<tr class="hide" >
<td width="40" height="20">row 1</td>
</tr>
<tr>
<td width="40" height="20">row 2</td>
</tr>
<tr class="hide">
<td width="40" height="20">row 3</td>
</tr>
<tr>
<td width="40" height="20">row 4</td>
</tr>
<tr class="hide">
<td width="40" height="20">row 5</td>
</tr>
</table><br>
<button type="button" name="HideRows">Hide Odd Rows</button>
<script type="text/javascript" src="hideOddRows.js"></script>
</body>
</html>
Questions
I could not manage to place
script
tag inhead
due to DOM loading issue. How do I improve this solution to placescript
tag inhead
?Can I improve the HTML code?
Note: I've yet to learn jQuery.