I would like to set an element content in case it is empty. The html.erb code is below:
<% if micropost.comments.any? %>
Solution 1:
A non-existent DOM element is considered by JavaScript as an object with length = 0. It is possible to verify this by using a web browser console, writing the DOM element and checking the console output. Choose a micropost without comments (say micropost with id = 304): micropost.comments.any? would be false and everything inside div.comments-section will not appear in the document. Open the console and write the following code at the prompt:
The original if statement does not work because the object is not null and having length = 0. Therefore the right if statement is: if (comments.length == 0)
Solution 1:
A non-existent DOM element is considered by JavaScript as an object with
length = 0
. It is possible to verify this by using a web browser console, writing the DOM element and checking the console output. Choose a micropost without comments (say micropost withid = 304
):micropost.comments.any?
would be false and everything insidediv.comments-section
will not appear in the document. Open the console and write the following code at the prompt:$('ol#comments_micropost-304');
The output will be:
[]
in a Chromium based browserObject { length: 0, prevObject: Object, context: HTMLDocument → 1, selector: "ol#comments_micropost-304" }
in FirefoxThe original
if
statement does not work because the object is not null and havinglength = 0
. Therefore the right if statement is:if (comments.length == 0)