Jquery Uncaught TypeError: Unable to read "replace" property from undefined

Anyone can tell me why I get this error:

Uncaught TypeError: Unable to read the "replace" property from 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(); 
+5
source share
1 answer

I believe this error is caused by one of two scenarios based on the above information:

  • $('#NewPostBody) not found in the DOM

  • $('#NewPostBody) is, but does not have a class attribute.

This can be solved using the following method:

 var pid = ($('#NewPostBody').length && $('#NewPostBody').attr('class')) ? $('#NewPostBody').attr('class') : ""; 

The ternary operator, together with the truth / falsification logic, should lead either to the returned class or to an empty string. In any case, pid.replace('post-t', '') can be safely called without causing an error.

+4
source

All Articles