DEV Community


Posted on

Moving conditionally-rendered DOM elements to a dynamic location on a page with jQuery

For my own reference, and perhaps of help to you, here is how I manipulated the position of DOM elements (a <div> tag displaying a status message) on a page when it gets rendered, based on the currently active element on the page. This allows for a shorter feedback loop from user action to status update, and keep user focus on what they are doing.

For this project, I had a controller action check status on the back end based on user input. The status message returned by the controller was best served directly in the relevant element that the user had tested, out of multiple possibilities.

As the project runs Rails, it displays status messages in the "Flash" message element in the view. It was this flash element I wished to move from the usual place at the top of the screen to the relevant "active" form the user had clicked on to check. So as to not repeat code conditionally and render flash messages specific to each controller method, I decided to use a quick JavaScript/jQuery hack to move the rendered message, encapsulated in its own HTML element, to within the currently-active page element, to give the user the closest feedback to what they needed to do.

The code itself is a declaration to run a function moveAlerts once the page loads. The moveAlerts function is a conditional that checks if there is an element called alert in the DOM, and if there is, it uses jQuery's prependTo method to add it to the top of a <div> that is classed as open.

The code is as follows, and in my case is in a in a "page-specific javascript" block in my view file:

  $( document ).ready( moveAlerts );

  function moveAlerts() {
    if (document.getElementsByClassName('alert').length) {
      $( 'div.alert' ).prependTo( '' );
Enter fullscreen mode Exit fullscreen mode

To use something like this yourself, you would need to edit it to correspond to elements in your document - you may want to move an element with a different name to "alert", or not have a <div> called "open" to move the alert into. Of course, if you are not using Rails, you would just need to put the <script> block in the HTML for your page rather than dealing with page-specific javascript blocks.

Top comments (0)