Anyone help me how to set the id for a div class dynamically in code. Let suppose class name by group_left

      <div class-"group_left article_left">

I have to add a id attribute for this class "group_left article left"

I have used the java script to set the id but I can't.This is my code.

   var thediv = document.getElementByClassName(".group-left ");
    thediv.setAttribute("id", "pad_id");

There is any way API to add attribute id for a class in drupal.please help me.

  • 1
    There are ways to add attributes via the Drupal API, but without knowing what type of element you are adding this attribute to and in what context, it is difficult to recommend a solution.
    – sheena_d
    Commented Feb 8, 2012 at 14:24

4 Answers 4


You would be better off using jQuery:

(function($) {
  $(function() {
    // Grab the element with both group_left and article_left class and set an ID attribute.
    $('.group_left.article_left').attr('id', 'pad_id');

It's worth checking that the element with both of those classes is unique on the page, if the same ID is added to more than one element then the document will become invalid and you might have problems with other javascript.

  • where to I have to add.
    – bharathi
    Commented Feb 8, 2012 at 10:58
  • In a javascript file :)
    – Clive
    Commented Feb 8, 2012 at 11:09
  • drupal.org/node/304255 :-)
    – Chapabu
    Commented Feb 8, 2012 at 15:24

I just came across this too, I used a simple rewrite in my view. Here are the details.

You can also use a template override, see this example.


I needed to stamp teasers with named anchors so to provide a jump-to behavior - I think you might dig into the node or field template and do something like:

<?php print '<div id="node-' . $node->type . '-' . $node->nid . '"></div>'; ?>

Just wanted to add how I had to add an ID to a div.class element in drupal. I tried what Clive put in and it didn't work for me. The below add it for me just fine.

jQuery(document).ready(function($) {
  // Code that uses jQuery's $ can follow here.
  $('div.field-print-link').attr('id', 'newsletterPrint');

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.