Need to hide two CSS IDs with one (script)

Viewed 56

I have a button on my page with the following code:

<h5 onclick="flightFunction()">One Way</h5>

<script type="text/javascript">
function flightFunction() {
  document.getElementById("returnDate").style.display = "none";
}

</script>

What I tried to do was just add a second document.getElementByID("rtField").style.display = "none"; (with the closure bracket) to the code, but when I click on the text, nothing happens. If I just add the code above, then one of the two elements is successfully hidden. However, I need the two elements (one using the returnDate CSS ID, the other using rtField CSS ID) both hidden at the same time when clicking the text. Is there a different code I should be using for this functionality?

3 Answers

This should work

<h5 onclick="flightFunction()">One Way</h5>

<script type="text/javascript">
function flightFunction() {
  document.getElementById("returnDate").style.display = "none";
document.getElementById("rtField").style.display = "none";
}

</script>

But always check the console for errors

Maybe some of the IDs are invalid, thus terminating the function

Just give them both the same class

<div id="returnDate" class="something">One Thing</div>
<div id="otherReturnDate" class="something">Two Things</div>

use the this keyword:

function flightFunction() {
    this.style.display = "none";
}

HTML:

<div id="rtField" onclick="flightFunction()">Hello</div>
<div id="returnDate" onclick="flightFunction()">Hello</div>

The this keyword will the object that invoked the function

Related