Java, Spring Boot, JSP
Goal: if an object is not added to the DOM remove some elements already present
IndexController.java
boolean isDeleteAddButtons = true;
if (isDeleteAddButtons) {
mv.addObject("this_might_work", true);
}
index.jsp ( assume the 3 elements are present and functional)
......
</body>
<script>
var isProof = '$(#this_might_work)';
if( typeof(isProof) === 'undefined') {
document.getElementById('popupBar_insert_add').remove();
document.getElementById('popupBand_insert_add').remove();
document.getElementById('popupEvent_insert_add').remove();
}
</script>
</html>
What am I doing wrong?
Type of a string will always be a string:
var isProof = '$(#this_might_work)';
console.log(typeof(isProof));
if (typeof(isProof) === 'undefined') {
document.getElementById('popupBar_insert_add').remove();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<div id="this_might_work"></div>
<div id="popupBar_insert_add">popupBar</div>
In jQuery $() will be an object:
var isProof = $('#this_might_work');
console.log(typeof(isProof));
if (typeof(isProof) === 'undefined') {
document.getElementById('popupBar_insert_add').remove();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<div id="this_might_work"></div>
<div id="popupBar_insert_add">popupBar</div>
The jQuery object can be empty or not. You can test this by getting the length:
var isProof = $('#this_might_work');
console.log(typeof(isProof));
if (isProof.length == 0) {
document.getElementById('popupBar_insert_add').remove();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<div></div>
<div id="popupBar_insert_add">popupBar</div>