0

I have a function that I want to execute relevant to the calling elements but I can't seem to the pass it as itself as a reference to the function I want to execute.

In short, this works

<div style="background-color:#444444">
    <button onclick="this.parentElement.style.display = 'none';">close</button>
</div>

And this does not

<script>
   function close() { this.parentElement.style.display = 'none'; }
</script>

<div style="background-color:#444444">
    <button onclick="close()">close</button>
</div>

Why is this and is there a way around it?

1
  • document.getElementsByTagName("button")[0].addEventListener("click", close) Commented Mar 9, 2016 at 19:55

3 Answers 3

1

Never mind, I'm an idiot

It seems I can simply pass the Element to the function with the this keyword

<script>
    function close(object) { object.parentElement.style.display = 'none'; }
</script>

<div style="background-color:#444444">
    <button onclick="close(this)">close</button>
</div>
Sign up to request clarification or add additional context in comments.

Comments

0

It's because in the close() function, this is the window object.

Try passing the element as argument:

<script>
    function close(btn) { btn.parentElement.style.display = 'none'; }
</script>

<div style="background-color:#444444">
    <button onclick="close(this)">close</button>
</div>

Comments

0

Off the top of my head, 'this' isn't pointing to the same object in the function as it is in the in-line code. You could pass 'this' in the function call, as in:

<script>
   function close(whichObj) { whichObj.parentElement.style.display = 'none'; }
</script>

<div style="background-color:#444444">
    <button onclick="close(this)">close</button>

HTH, Jim

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.