DOM still applies in SharePoint

There’s so much to remember when dealing with the DOM, especially when in SharePoint.  I am writing this post so I don’t forget and go searching “again”.  Here’s the scenario,  I needed to get data from a list and populate an html dashboard that will be rendered to a SharePoint page.  I use REST API and jQuery AJAX to retrieve my data so I can place it in the right place.  Below is my initial code and the error I was receiving.

    var endPointUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbyTitle('dashboard')/items";

    var fieldStaff=document.querySelector("#fieldStaff");    

$.ajax({
    url: endPointUrl,
    type: "GET",
    headers: {
    "accept": "application/json;odata=verbose"
},
}).success(function (data) {
               fieldStaff.appendChild(data.d.results[0].FieldStaff);
});

The code produced the following error:
Uncaught TypeError: Failed to execute ‘appendChild’ on ‘Node’: parameter 1 is not of type ‘Node’.

It’s complaining that the parameter, data.d.results[0].FieldStaff is not a node, which means I need to make it a node.  But how?  After a little digging, I remembered that every HTML webpage gets parsed into a tree like structure of node objects and everything becomes a node(elements, text, etc.), so the value of data.d.results[0].FieldStaff must be a node.  The code below shows how I turned it into a node using the DOM API document.createTextNode().

    var endPointUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbyTitle('dashboard')/items";
var fieldStaff=document.querySelector("#fieldStaff");    

$.ajax({
    url: endPointUrl,
    type: "GET",
    headers: {
    "accept": "application/json;odata=verbose"
},
}).success(function (data) {
      /*Make returned data a DOM Node*/
     var fieldStaffTextNode = document.createTextNode(data.d.results[0].FieldStaff);
     fieldStaff.appendChild(fieldStaffTextNode);

});

Error gone!

Thanks for reading!  Happy coding.

SharePoint SharePoint 2013

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: