GROW

code

Avoid DOM Manipulation

This issue is found automatically by CODA.
Time to fix: 01h 30min

What is DOM Manipulation?

Document Object Model, or DOM manipulation refers to the process of programmatically interacting with and modifying the structure, content, and style of a web page using JavaScript. Developers can add, remove, or change elements directly, allowing for dynamic and interactive elements that wouldn't be possible with static HTML alone.

Primarily, ServiceNow utilizes JavaScript for scripting on the Client-Side, which technically enables DOM manipulation. Within a given instance, it provides methods to interact with the DOM, such as the Glideform API or UI actions, for example.

Why is this an issue?

Being a web application, ServiceNow primarily delivers content and presents data to users through a browser. Various browsers utilize distinct engines to manage web content; for instance, Firefox relies on the Gecko browser engine, while iOS Safari uses the WebKit engine.

Browser engines may interpret and render document elements differently. At times, specific methods and functions may be supported by one engine but not by others, leading to potential variations in the way a web page is displayed across different browsers. This can result in unexpected behavior for the same web page when rendered in various browsers. For instance, consider the following example:

1
2
3
4
5
function onLoad() {
  // Assuming 'sys_target_table' is the field containing the table name
  var tableName = document.getElementById('sys_target_table').value;
  console.log('Table Name:', tableName);
}

When manipulating DOM elements, interactions often involve classes and IDs. The risk arises that ServiceNow may alter these names in a future update, potentially causing the script to no longer function as anticipated.

How do I fix it?

The solution for this issue can vary depending on what one is trying to accomplish; however, usually, it will be necessary to adjust the DOM manipulation. A better alternative to DOM manipulation is the GlideForm API, known as g_form. For instance, in the previous section's code snippet, it would be a good idea to update the method with something like this:

1
2
3
4
5
6
//Get the table name
function onLoad() {
    if (g_form.isNewRecord()) {
        var tableName = g_form.getTableName(); 
    }
}