Find Name of CSS Class

Discussion in 'JavaScript' started by hovesh07, Nov 5, 2009.

  1. #1
    Hi All,

    How do I use JS to find the name of a CSS class?
    If a CSS class is named MyClassxxxx, where xxxx can change from page-to-page, how can I find the class name?
    I eventually want to change the class' font characteristics.

    Thanks!
     
    hovesh07, Nov 5, 2009 IP
  2. dimitar christoff

    dimitar christoff Active Member

    Messages:
    882
    Likes Received:
    62
    Best Answers:
    0
    Trophy Points:
    90
    #2
    well, you can do
    
    var elClass = document.getElementById("someid").className.replace("MyClass", "");
    
    alert(elClass); // alerts xxxx
    Code (javascript):
    although to change the font all you'd need to do is either apply an new className or access the el.style collection and change the fontFamily property.
     
    dimitar christoff, Nov 5, 2009 IP
  3. hovesh07

    hovesh07 Well-Known Member

    Messages:
    389
    Likes Received:
    4
    Best Answers:
    0
    Trophy Points:
    108
    #3
    Thanks for the reply.
    However, I don't know the full name of the class. I only know it starts with "MyClass" and has 4 digits added on. I don't know what the 4 digits are at runtime.
     
    hovesh07, Nov 6, 2009 IP
  4. dimitar christoff

    dimitar christoff Active Member

    Messages:
    882
    Likes Received:
    62
    Best Answers:
    0
    Trophy Points:
    90
    #4
    mate - this is EXACTLY the point. the script above will return the dynamic 4 digits you refer to, it does not need to know them.

    this will only work if the class name starts with MyClass and it has no other classes appended to it. otherwise - some more regex will be needed. if your script needs the last 4 digits based upon an event, then for a click fit can be something like this:

    
    <td class="MyClass3431" onclick="handleClick(this);">
    some content
    </td>
    
    ...
    
    <script type="text/javascript">
    var handleClick = function(el) {
        var last4digits = el.className.replace("MyClass", "");    
        // do something with them ...
        alert(last4digits); // alerts 3431
    };
    </script>
    Code (javascript):
     
    Last edited: Nov 6, 2009
    dimitar christoff, Nov 6, 2009 IP