jensengar
jensengar

Reputation: 6167

Accessing parentNode with button

I am trying to access the parentNode of a button element (div) but I get an error every time. Here is what I am trying to do. Simply put, this is a page that had 2 divs on it. I only want one div displayed at a time. There is a button on the first page that switches to the second and a button on the second that is supposed to return to the first (but doesn't because it can't locate the parentNode).

        <div class="pageContent" id="page_3">
            <div class="primaryPage" id="primaryPage_3">
                <h2>Bills_______________________</h2>
                <p>Here are my monthly Bills<br><br>blah blah</p>
                <button type="button" id="billButton" onclick="newBill()">Add Bill</button>
            </div>
            <div class="pageContent" id="billPage">
                <p>this is the bill page</p>
                <button class="backButton" onclick="back()">Back</button>
            </div>
        </div>

function newBill(){
document.getElementById("primaryPage_3").style.display = "none";
document.getElementById("billPage").style.display = "block";
document.getElementById("billPage").setAttribute("back", "primaryPage_3");
}

function back(){
var previousPage = this.parentNode.getAttribute("back");
this.parentNode.style.display = "none";    
document.getElementById(previousPage).style.display = "block";
}

Upvotes: 0

Views: 853

Answers (1)

user1106925
user1106925

Reputation:

Change this...

onclick="back()"

to this...

onclick="back.call(this)"

Invoking a function using .call() lets you manually set the calling context (the this value) of the function being invoked. Here it's setting it to the current element.

Upvotes: 1

Related Questions