Anyone can tell me why i am getting this error:
Uncaught TypeError: Cannot read property 'replace' of undefined
function checkNewPost(x) {
var pid = $('#NewPostbody').attr('class');
if(pid === 'post-t') {
setTimeout(checkNewPost, <?php echo $p_id; ?>);
} else {
$.ajax({
type: "POST",
url: "/html_postReply.php",
data: "pid="+pid.replace('post-t', '')+"&type=1",
success: function(html) {
if(html) {
$('.tekin').append(html);
jQuery("span.timeago").timeago();
$(".tekin").scrollTop($(".tekin")[0].scrollHeight);
}
if(!x) {
setTimeout(checkNewPost, <?php echo $p_id; ?>);
}
}
});
}
}
checkNewPost();
To fix the “cannot read property of undefined” error, use the optional chaining operator on the variable before accessing a property. If the variable is undefined or null , the operator will return undefined immediately and prevent the property access.
To replace undefined with a empty string with JavaScript, we can use the || operator to return a default if its left operand is undefined .
I believe that this error is caused by one of two scenarios, based on the given information above:
$('#NewPostBody)
is not being found in the DOM
$('#NewPostBody)
is being found but has no class attribute.
This can be solved using the following method:
var pid = ($('#NewPostBody').length && $('#NewPostBody').attr('class'))
? $('#NewPostBody').attr('class')
: "";
The ternary operator along with truthy/falsy logic should result in either the class being returned or an empty string. Either way, pid.replace('post-t', '')
can safely be called without resulting in an error.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With