javascriptsharepointcsomsharepoint-jsom

How to retrieve list items title using JavaScript


I'm trying to retrieve list items Title to insert it into a div section in my SharePoint home page, I've found this code which retrieve item URL.

it works just fine.

var clientContext = SP.ClientContext.get_current();
var list = clientContext.get_web().get_lists().getByTitle("Artdesk alertes");

var caml = new SP.CamlQuery();
caml.set_viewXml("<View />");

var listItemCollection = list.getItems(caml);

clientContext.load(list, "DefaultDisplayFormUrl");
clientContext.load(listItemCollection);

clientContext.executeQueryAsync(function() {

    for(var i in listItemCollection.get_data()) {

        console.log( "DispFormRelativeUrl: " + list.get_defaultDisplayFormUrl() + "?ID=" +listItemCollection.get_data()[i].get_id() );
    }

}, function(sender, args) {
    window.console && console.log(args.get_message());  
});

How do I get the list item Title using the JavaScript object model?


Solution

  • clientContext.load(list, "DefaultDisplayFormUrl");
    

    You are requesting "DefaultDisplayFormUrl" property here. You can specify Title property or just remove requesting specific properties to get every one of them (not recommended - you must request only those you need to reduce load). So it will be clientContext.load(list, "Title") or clientContext.load(list);

    clientContext.executeQueryAsync(function() {    
        var listItemEnumerator = collListItem.getEnumerator();
        while (listItemEnumerator.moveNext()) {
            var oListItem = listItemEnumerator.get_current();       
            console.log("List Title", oListItem.get_item('Title'));
        }
    }, <...>);
    

    Note that you can get any property via get_item method (but you must request to load that property or it will throw an exception).

    Here is the working code:

    var clientContext = SP.ClientContext.get_current();
    var list = clientContext.get_web().get_lists().getByTitle("Artdesk alertes");
    
    var caml = new SP.CamlQuery();
    caml.set_viewXml(""); // empty query also works
    
    var listItemCollection = list.getItems(caml);
    
    clientContext.load(listItemCollection); // i requested every property
    
    clientContext.executeQueryAsync(function() {
        var listItemEnumerator = listItemCollection.getEnumerator();
    
        while (listItemEnumerator.moveNext()) {
            var oListItem = listItemEnumerator.get_current();
            console.log(oListItem.get_item('Title'));
        }
    
    }, function(sender, args) {
        window.console && console.log(args.get_message());  
    });