My situation is as follows: I have a script file (somescript.js) that is included in the page and another snippet of code in the same page. On the page I have two buttons, the first one calls the snippet of code and it removes an element with remove() and the other calls a function from the script file, that checks if the respective element that was removed is still present. The problem is that it still finds that element. How can I solve this?
The snipped of code is:
<script language="javascript" type="text/javascript" src="jquery.js"></script>
<script language="javascript" type="text/javascript" src="somescript.js"></script>
<script language="javascript" type="text/javascript">
$(document).ready(function() {
/* used by the second button to call the checking function */
$("#button2").live("click", function(e){ someFunction(); });
/* if the control is here, it works, but if it's called from the inserted file (somescript.js), it doesn't */
$("#button2").live("click", function(){
if ($("#somediv").length == 0) {
alert("Element missing");
}
});
/* used by the first button to remove the element */
$("#button1").live("click",function() {
$("#somediv").remove();
});
});
</script>
While the function from the somescript.js file is:
function someFunction() {
if ($("#somediv").length > 0) {
alert("Alert message");
}
}
And I’m getting the alert message. What am I doing wrong?
Update:
I’ve added the same code in the snippet of code inside the page (see the code above) and this way it works. But it still doesn’t work when it resides in the included file (somescript.js). What am I missing?????
Here is what you want to do.
The reason you should check for undefined instead of length is because in some cases if the element doesn’t exist how will
.lengthexist? You will get an error saying ‘length’ is an invalid function of undefined.Edit:
Also remove the
language=javascriptfrom your script tags. It should just be<script type="text/javascript" src="somefile.js"></script>Also if you are still getting the message you may want to
console.log($('#someDiv'));to see what is going on. It could be you have 2 elements with the same id and when one is removed your script is seeing the last remaining element with that ID. Since ID’s are supposed to be unique when you do a .remove() only the first element with the given ID is removed.