Reputation: 21002
I am using the instagram API and if a caption doesnt exist or doesnt have text it doesnt include the node at all. So I included a check to see if caption exists which works, but if caption exists and the child node text does not, then I get the error: Uncaught TypeError: Cannot read property 'text' of null
.
This is my code:
for (p in pictures) {
if (pictures[p].hasOwnProperty('caption')) {
if (pictures[p].caption.text != null) {
captionString = pictures[p].caption.text;
}
}
}
Upvotes: 1
Views: 48
Reputation: 7326
Apparently, the caption
property exists, but it seems to be null
for some cases, and when you evaluate (null).text
, you are getting the error detailed in your question.
Add pictures[p].caption &&
to evaluate for caption
in your inner if
.
This should work for you (note that I also merge your two if
s and I did all evaluations in only one if
):
for(p in pictures) {
if (pictures[p].hasOwnProperty('caption') && pictures[p].caption && pictures[p].caption.text != null) {
captionString = pictures[p].caption.text;
}
}
Upvotes: 2
Reputation: 4997
you could just try :
if(pictures[p].caption != null){
captionString = pictures[p].caption.text;
}
instead of
if(pictures[p].hasOwnProperty('caption')){
if(pictures[p].caption.text != null){
captionString = pictures[p].caption.text;
}
}
Because the caption property is always here, but may be null if not available
Upvotes: 0