Search This Blog

Thursday, September 19, 2013

Client object Model: Content Editor Sharepoint list and display on a page

1) Add content editor webpart on page.

2) Add the below content in the content editor webpart: Here I want to create a list (with ul, li tags) having an anchor tag (text fetched from "title" column) which points to a URL fetched from a column of the list. Also the css class to be applied on each <li> tag is fetched from a custom column.

<div class="testcss">
        <li><a href="#my-quick-links">Quick links</a></li>
    <div id="my-quick-links">
<script type="text/javascript">

    //We need to run our function only after sp.js file loads
    ExecuteOrDelayUntilScriptLoaded(ViewItem, "sp.js");
    function ViewItem() {
        var context = new SP.ClientContext.get_current();
        var web = context.get_web();
        var list = web.get_lists().getByTitle('QuickLinksHome');

        //It will fetch all the items from the list
        var myquery = new SP.CamlQuery.createAllItemsQuery();
        myItems = list.getItems(myquery);

        //If the items load correctly then success function will be called
        context.executeQueryAsync(Function.createDelegate(this, this.success), Function.createDelegate(this, this.failed));

    function success() {
        var text = "";
        var LinkURL = "";
        var TextURL = "";
        var cssClass = "";
        var Active = "";
        var ListEnumerator = this.myItems.getEnumerator();
        text = '<ul>';
        while (ListEnumerator.moveNext()) {
            //Will get the current row from the SP List
            var currentItem = ListEnumerator.get_current();
            Active = currentItem.get_item('IsActive');
            if (Active == "Yes") {
                //Will get the "Url" column from the current row
                LinkURL = currentItem.get_item('Link');

                TextURL = currentItem.get_item('Title');

                //String is formed with links pointing to URLs with css applied
                text = text + '<li class="loop-quick-links">';
                text = text + ('<a href="' + LinkURL + '">' + TextURL + '</a></li>');
        text = text + '</ul>';

        //Getting the empty div tag
        fieldNameElement = document.getElementById('loop-quick-links');

        //Assign the string formed to the div element's innerHTMl to display on page
        fieldNameElement.innerHTML = text;

    function failed(sender, args) {
        alert("failed. Message:" + args.get_message());



  1. This is a great example except the document.getElementById('loop-quick-links') doesn't match the div id at the top (my-quick-links). They need to match or it fails.

    1.'s should be document.getElementById('my-quick-links') as