JavaScript Dynamically Create an Image Element

Sitebee

Technical SEO
Staff member
Code:
<script>
// JS function to dynamically inject an image element after the H1 heading tag.
  (function() {
    // Create the new IMG element variable
    var img = document.createElement('img');

    // Add the img src content
    img.src = "https://sitebee.co.uk/assets/images/sb_logo_22.jpg";

    // Create the variable to inject after H1 element
    var h1 = document.querySelector('h1');
   
    // Inject the new IMG elements after the H1 element
    if (h1) {
      h1.parentElement.insertBefore(img, h1.nextSibling); }

  }) ();
</script>