Jump to content

Some document functions do not want to run directly from inside onclick="alert(...)"


Mike3456

Recommended Posts

I tried to run getElementById() directly from onclick="alert(...)" and it does not work! The alert does not even pop up!

 

I ran it indirectly from my JS function myTest() then it works fine.

 

I also ran another function document.hasFocus() directly from onclick="alert(...)" and it works fine.

 

So what is so unique about getElementById() such that onclick= cannot handle?

 

 

 

 

 

 

================================================

<!DOCTYPE html>
<html>
<head>

</head>


<body>

<p id="p1">Test 1</p>

<button type="button" onclick="myTest()">myTest()</button>

<button type="button" onclick="alert(document.hasFocus())">hasFocus()</button>

<button type="button" onclick="alert(document.getElementById("p1").tagName)">getElementById()</button>

<script>
function myTest() {
alert(document.getElementById("p1").tagName);
}
</script>

</body>
</html>

 

 

 

Link to comment
Share on other sites

If you use an editor with syntax highlighting, or put that snippet in code blocks, you might see the issue that DaveJ is referring too

<!DOCTYPE html>
<html>
<head>

</head>


<body>

<p id="p1">Test 1</p>

<button type="button" onclick="myTest()">myTest()</button>

<button type="button" onclick="alert(document.hasFocus())">hasFocus()</button>

<button type="button" onclick="alert(document.getElementById("p1").tagName)">getElementById()</button>

<script>
function myTest() {
    alert(document.getElementById("p1").tagName);
}
</script>

</body>
</html>
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...