Drupal - How to get the node ID in jQuery/JavaScript
As mentioned above, Drupal core has no use for the node ID on the client side so it doesn't pass it through. if you want access to it you'll need to add it manually:
function MYMODULE_node_view($node, $view_mode, $langcode) {
if ($view_mode == 'full') {
$setting = array('MYMODULE' => array('currentNid' => $node->nid));
$node->content['#attached']['js'][] = array(
'data' => $setting,
'type' => 'setting',
);
}
}
Then on the client side you'll have access to it through Drupal.settings
:
var currentNid = Drupal.settings.MYMODULE.currentNid;
As mentioned by MPD in his answer, working with the default css-classes Drupal generates for the element is a easy solution which works without custom PHP code.
Here is our implementation:
(function($) {
/**
* Find Drupal Node ID based on <body> element classes.
*
* @return Node ID or false
**/
function getCurrentNodeId() {
var $body = $('body.page-node');
if ( ! $body.length )
return false;
var bodyClasses = $body.attr('class').split(/\s+/);
for ( i in bodyClasses ) {
var c = bodyClasses[i];
if ( c.length > 10 && c.substring(0, 10) === "page-node-" )
return parseInt(c.substring(10), 10);
}
return false;
}
/**
* Example usage...
*
**/
Drupal.behaviors.yourModuleNameHere = {
var nodeId = getCurrentNodeId();
if ( nodeId ) {
// Node ID found.
// ...do something with it.
} else {
// Node ID not found. Guess we are not on a node page
// ...handle this case with care too.
}
}
}(jQuery);
The default template_preprocess_html()
has this bit of code in in
if ($suggestions = theme_get_suggestions(arg(), 'page', '-')) {
foreach ($suggestions as $suggestion) {
if ($suggestion != 'page-front') {
// Add current suggestion to page classes to make it possible to theme
// the page depending on the current page type (e.g. node, admin, user,
// etc.) as well as more specific data like node-12 or node-edit.
$variables['classes_array'][] = drupal_html_class($suggestion);
}
}
}
This will stick on classes to the <body>
element line page-node-123
. If you don't want to use your own code in a custom module, you can get the classes via jQuery, find the one that matches page-node-
, and then parse out the nid.