function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion

Determine Record's Object Type w/ Javascript or jQuery

Can someone suggest a way to retrive the object type of a current record using JS or jQuery only?


You can call sforce.connection.getGlobalDescribe(), then iterate through the results, calling getDescribe() on each object, checking getKeyPrefix() against the first three characters of the ID value you're testing for. Use caching for performance, if using multiple ID values.


If this is going to be in Visualforce, you could also use a @RemoteAction function, passing the ID value as a parameter, calling getSObjectType() on that in Apex Code, and returning the result back to the page. Since key prefixes are dynamic across orgs (especially related to custom objects), you need to use either describe information and/or Apex Code.


Thanks sfdcfox!

Let me give this a shot.


Works great!

Is there a better way to grab the current record's ID than this?

function getRecID(){
    return String(window.location.pathname.match(/\w{15}|\.com\/\w{18}/));




That's basically how I've done it in the past (when I didn't have access to Visualforce, for example). But, you should be aware that there may be conditions where the ID would be in a different location (e.g. in a Visualforce page, it will usually be a URL parameter: "id=<recordId>"). I would probably instead do this, though:



The last 3 characters will (usually) only appear when a redirection has occurred from a Visualforce page (since the API always uses the 18 character ID values); you can safely ignore these three extra characters. Note that some Visualforce pages might lose the record ID after an AJAX refresh.