Web Analytics Made Easy -
StatCounter get a list of ID that uses CLASS - CodingForum

Announcement

Collapse
No announcement yet.

get a list of ID that uses CLASS

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

  • get a list of ID that uses CLASS

    in javascript, is it possible to get a list of

    ID that uses a particular CLASS?

    example same class, different id
    and i want to get a list of ID that uses the class tab

    <td id="td2" class="tab" width="100" >
    <td id="td3" class="tab" width="100" >
    <td id="td4" class="tab" width="100" >

  • #2
    Code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml" >
    <head>
        <title>Untitled Page</title>
        <style type="text/css">
        .tab {
        width:100px;
        }
        </style>
        <script type="text/javascript">
        function getId()
        {
            var thetd = document.getElementsByTagName('td');
            for(var i = 0; i < thetd.length; i++)
            {
                if(thetd[i].className == 'tab')
                {
                    alert(thetd[i].getAttribute('id'));
                }
            }
        }
        window.onload = getId;
        </script>
    </head>
    <body>
    <table border="0" cellpadding="0" cellspacing="0">
    <tr>
    <td id="td1" class="tab">td 1</td>
    <td id="td2" class="tab">td 2</td>
    <td id="td3" class="tab">td 3</td>
    </tr>
    </table>
    </body>
    </html>
    ||||If you are getting paid to do a job, don't ask for help on it!||||

    Comment


    • #3
      The trouble with Aero's code is it will only find the elements whose
      className is set to the target class only- it will omit any elements with
      more than a single class.

      This function returns an array of elements - you can fill the array with id's instead,
      but generally you are interested in the elements.

      You can limit the search by tag name or parent element, if you choose.

      Code:
      function classNameArray(str,wot,pa){
      	if(!pa) pa= document.body;
      	if(!wot) wot= '*';
      	var rx= new RegExp('\\b'+ str+ '\\b');
      	var A= [], tem, temp;	
      	var who= pa.getElementsByTagName(wot);
      	var L= who.length;
      
      	for(var i= 0; i< L; i++){
      		tem= who[i];
      		temp= tem.className;
      		if(!temp) continue;
      		if(rx.test(temp)) A.push(tem);
      	}
      	return A;
      }
      Last edited by mrhoo; Oct 2, 2006, 10:24 PM.

      Comment


      • #4
        I wasn't going by what the op posted and since they didn't say there were elements with multiple classes I didn't write code for it.
        ||||If you are getting paid to do a job, don't ask for help on it!||||

        Comment

        Working...
        X