Brett T Brett T -4 years ago 97
HTML Question

Adding a line break before a div in javascript

I have a JavaScript function that runs when an html button is clicked. If an error occurs in the function i display an error which is just an html div that i add text to dynamically and is usually hidden until the error occurs. I would like to dynamically add a line break (br) before the error display (before the div) at the same time.

My issue is that, if the user keeps clicking the button and an error keeps occurring, the page fills up with line breaks and the rest of the page moves down. So the breaks are compounding and never going away. Here is the JavaScript which dynamically adds the error text to the div and a line break before it.

$('#sku-upc-error').html(jqXHR.responseText).before("<br />");


Here is the html that displays the error.

<div class="error-display" id="sku-upc-error"></div>


I can hide or remove the div dynamically, when the error doesn't occur but the line breaks are still there. like this for example:

$("#sku-upc-error").hide();


Is there a way to remove the line breaks too? Or a better way to add the breaks before the error div so that they don't stay on the page and compound if errors keep occurring?

Answer Source

You can, here is a neat little trick.

When you add the line breaks, add a class to them like so...

$('#sku-upc-error').html(jqXHR.responseText).before("<br class='break' />");

Then when you run the code to hide the error message, include this code directly after it to remove the line breaks.

$(".break").remove();

Give that a try and let me know how you get on. You can also use .hide() if you wanted but this removes them all from the DOM properly rather than hiding them but keeping them within the markup.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download