Skip to content Skip to sidebar Skip to footer

Working Jquery Code Not Working Inside Conditional

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:

    $('ol#comments_micropost-304');
    

    The output will be:

    1. [] in a Chromium based browser
    2. Object { length: 0, prevObject: Object, context: HTMLDocument → 1, selector: "ol#comments_micropost-304" } in Firefox

    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)

Post a Comment for "Working Jquery Code Not Working Inside Conditional"