Reputation: 247
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
if (document.getElementById("popup")) {
window.alert("hi");
}
</script>
</head>
<body>
<h1 id="popup">dfdfs</h1>
</body>
</html>
i have a simple javascript which shows alert when the h1 id exits ,but i am not getting the alert message.code in jquery also can help.
Upvotes: 0
Views: 2995
Reputation: 87233
Because, you're executing the script
before document
is completely loaded, the element #popup
is not found.
Use DOMContentLoaded
to check if the DOM
is completely loaded.
<script type="text/javascript">
document.addEventListener("DOMContentLoaded", function(event) {
console.log("DOM fully loaded and parsed");
if (document.getElementById("popup")) {
window.alert("hi");
}
});
</script>
ready
Using jQuery
, you can use ready
method to check if DOM
is ready.
$(document).ready(function() {
if ($("#popup").length) {
window.alert("hi");
}
});
script
to the end of body
You can move your script
to the end of body
.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1 id="popup">dfdfs</h1>
// Move it here
<script type="text/javascript">
if (document.getElementById("popup")) {
window.alert("hi");
}
</script>
</body>
</html>
Upvotes: 2
Reputation: 597
It is good practice to use the <script>
tags in <body>
because it improves the performance by loading it quicker.
And then use
<body>
<script>
$(function() {
if(document.getElementById("popup")) {
window.alert("hi");
}
});
</script>
</body>
Upvotes: 0
Reputation: 3148
Write your script
after the element so that it runs after element is present. See the code:
<!DOCTYPE html>
<html>
<body>
<h1 id="popup">dfdfs</h1>
<script type="text/javascript">
if (document.getElementById("popup")) {
window.alert("hi");
}
</script>
</body>
</html>
Plunkr for the same is: "http://plnkr.co/edit/0fznytLHtKNuZNqFjd5G?p=preview"
Upvotes: 2
Reputation: 8858
Put your <script>
tag at the end of the body
:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1 id="popup">dfdfs</h1>
<script type="text/javascript">
if (document.getElementById("popup")) {
window.alert("hi");
}
</script>
</body>
</html>
Upvotes: 3
Reputation: 139
Below code gives you solution
$(document).ready(function() {
if (document.getElementById("popup")) {
window.alert("hi");
}
});
Upvotes: -1
Reputation: 3580
try this easy way. no need of jquery.
<html>
<head>
</head>
<body>
<h1 id="popup">dfdfs</h1>
<script type="text/javascript">
if(document.getElementById("popup")) {
window.alert("hi");
}
</script>
</body>
</html>
Upvotes: 0
Reputation: 7511
Your script is above the h1
element that you're trying to retrieve. Because of this, it is being run before the element actually exists.
Either move the script to the bottom of the page, or wrap it in a jQuery ready block. And consider moving it to an external file.
$(function() {
if(document.getElementById("popup")) {
window.alert("hi");
}
});
Upvotes: 0