Microsoft SharePoint and .NET Technology Insight

SharePoint, .NET, Office365, Windows Azure, TFS, Project Server and SQL Server Technology Insights

Leave a comment

Dynamically updating markup within a SharePoint 2010 Content Editor Web-Part (CEWP) using JavaScript

Here is an example of dynamically updating URL links within a SharePoint 2010 Content Editor Web-Part (CEWP) and reading the values from a SharePoint list using JavaScript.

<script type="text/javascript">

var clientContext = null;
var web = null;
ExecuteOrDelayUntilScriptLoaded(GetMyTimeSheetURL, "sp.js");

function GetMyTimeSheetURL()
 clientContext = new SP.ClientContext.get_current();
 web = clientContext.get_web();
 var list = web.get_lists().getByTitle('Popular Links');

var camlQuery = new SP.CamlQuery();
 camlQuery.set_viewXml('<View><Query><Where><Eq><FieldRef Name="Title"/><Value Type="Text">My Timesheet</Value></Eq></Where></Query><ViewFields><FieldRef Name="LinkUrl" /></ViewFields></View>');

this.listItems = list.getItems(camlQuery);
 clientContext.executeQueryAsync(Function.createDelegate(this, this.onListItemsLoadSuccess),
 Function.createDelegate(this, this.onQueryFailed));



function onListItemsLoadSuccess(sender, args) {
 var enumerator = this.listItems.getEnumerator();
 while (enumerator.moveNext()) {
 var item = enumerator.get_current();
 var url = item.get_item('LinkUrl')
 document.getElementById("contentDiv").innerHTML ='<li><a href= ' + url + '>My TimeSheet</a></li>';
function onQueryFailed(sender, args) {
alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());}


<div class="resources-box"><h3>Key Resources</h3>
<div id="contentDiv"><li><a href="#">My TimeSheet</a></li></div></ul></div>


The above markup can be added into a CEWP and utilizes the SharePoint 2010 JavaScript Client Object Model Features to dynamically update the URL links within the web-part based on values in a SharePoint list.  The JavaScript delegate onListItemsLoadSuccess does not return a value which is why the above code utilizes document.getElementById(“contentDiv”).innerHTML to update the markup for the HREF tag.