Reputation: 51
I am trying to test to see if I can have a function to dynamically add an element along with its ID via Jquery if it is missing in HTML, but it does not show up as null or undefined, so I can't get it to create itself.
HTML
<div id="player">
<p>Player</p>
<!--<p id="pName"></p>-->
</div>
Javascript
function CCPlayer (player) {
switch (player) {
case 'Name': {
if ('#pName' == undefined) {
alert('1')
$('#player').prepend('<p id="pName"></p>')
} else if ('#pName' == null) {
alert('2')
$('#pName').html('<p>Name: ' + pn + '</p>')
}
} break
CCPlayer('Name')
The one that shows null is supposed to be != in order for alert 2 to show up when an element is already present, but alert 1 does not show up, so I mark it as undefined and null in both scenario, but no alert shows up when an element is not present in HTML, so that means when it checks for missing element, it somehow is not null neither undefined as I was expecting it to be. So, what am I suppose to put down to search for a missing element, and if it not there, return an alert that it not there.
Upvotes: 0
Views: 129
Reputation: 64657
You are checking if the string '#pName'
is undefined
or null
- it never will be. I think you want to do:
if ($('#pName').length === 0) {
//...
} else if ($('#pName').html().length === 0) {
//...
}
Upvotes: 2