How-to: Overhaul the DOM

Changing a design by tweaking existing CSS is one thing, but sometimes you simply need to throw out a lot of the existing markup and insert your own.

Method 1 — Brute force

The most cumbersome, yet straightforward, way is to just pile up your jQuery selectors and change markup:

// Remove elements from the page
$('.myClassName').remove()

// Change DOM nodes
$('a.signup').text("Join")
$('#header').html('<header><h1 class="h1">My new title</h1></header>')

// Add HTML
$('.myClassName').append("<div class='panel'><h1>Heading</h1><p>Description</p>")
$('.myClassName').after("<div class='panel'><h1>Heading</h1><p>Description</p>")

Method 2 — Create a template

Another option is to create your markup using a string, and then inject that as markup. Since Labcoat runs only in modern browsers, you can use a nice feature from new Javascript that isn’t available in all browsers — multi-line strings. Much easier to write and read:

var newPanelHTML = `
  <div class='panel'>
    <h1>Heading</h1>
    <p>Description</p>
  </div>`

Then simply insert it the normal way:

$('selector').append(newPanelHTML)

This technique can be extended to include string interpolation and more, learn about Template Literals on MDN.

Method 3 — Fake it ‘till you make it (use screenshots)

Use Photoshop to create an image of the bit you want to insert. Unfortunately, you’ll need to host the image somewhere (S3, local webserver).

$('form#login').html('<img src="http://localhost:3000/new-login-form.png">');

Method 4 — Use an <iframe>

This is a bit further afield, but another option is to replace a DOM node with an <iframe> pointing it to some HTML hosted elsewhere. For example, you might have a local webserver hosting your new markup:

$('#navigation').html('<iframe src="http://localhost:3000/navigation.html" width="100%" height="100"></iframe>')

In addition to bringing in HTML, this can also bring in its own JS and CSS. So in this example, you can try your new Navigation Bar on the existing site in one line.



Do you have any suggestions for how to improve this (or any) documentation?
Send an email to support@labcoat.io