Replying to myself. I wrapped the .innerHTML call in a try/catch block
<script type="text/javascript">
var x = document.getElementsByClassName("page-not-found");
var search = '<div class="page-not-found-search-top"><h2>Search this site</h2><p></p><form action="/search" id="discourse-search"><input type="text" name="q" value=""><button class="btn btn-primary">Search</button></form><p></p></div>'
try {
x.item(0).innerHTML += search
} catch (error) {
}
</script>