AnsweredAssumed Answered

Creating child elements with javascript and defensive programming

Question asked by Tiffany Taylor on Jul 24, 2015
Latest reply on Aug 25, 2015 by Tiffany Taylor

Hello,

 

I experienced my first test environment reset.  There was something I noticed after the reset that I thought was odd, and I'm not sure if it's something I need to work out with my javascript.  I was hoping someone here would be able to help or elaborate more on the subject.

 

Here is the entirety of my javascript added to Canvas:

// function that injects a node into the DOM that can be manipulated with CSS

function inject_node(target_id, node_element, node_id){

  "use strict";

  var node = document.createElement(node_element);

  node.id = node_id;

  var target_element = document.getElementById(target_id);

  var parent_element = target_element.parentNode;

  parent_element.insertBefore(node, target_element);

}

 

// injected elements in Canvas

inject_node("identity", "div", "jwcc-slashes");

inject_node("login_form", "p", "online-courses");

 

So I have the function, inject_node to add a node to the DOM, that I can style with CSS.  My area of concern is the jwcc-slashes, which are just some graphical pizzazz that I've added to our banner.

 

Below is the CSS for jwcc-slashes:

/* the forward slashes on the far right that separates the banner from user menu */

div#jwcc-slashes{

  float: left;

  background-image: url("/assets/education/images/forward-slashes-transp.png?v2");

  background-repeat: no-repeat;

  background-size: auto 75px;

  height: 75px;

  width: 105px;

  margin-left: 61%;

  margin-top: 1px;

}

 

After the test environment reset, it appeared that my inject node function was ran twice.  My guess was that the test environment was cloned from production, which already had the node injected into the DOM, and then my javascript was re-ran, injecting the node a second time.  I logged into the test environment on Wednesday and saw two div nodes with jwcc-slashes, and the two nodes were stacking together, with the forward slashes in the banner, and forward slashes below the banner, messing up the overall design of the webpage.  The day after, Thursday, the second node was gone.

 

I'm curious if this is something I need to be concerned about.  Should I add something into my code that checks to see if the node with the specific ID already exists, and if not, then inject the node? I'm still inexperienced with javascript. so this is something that would take me a little time to think through and write out, and I don't want to have to spend the time, if it's something that may only affect the test environment in reset scenarios, and will not affect production ever.

 

Thanks for your time.

Outcomes