Find tags without a class using jQuery

September 18, 2008

A quick jQuery tip. I've recently added the excellent SyntaxHighlighter to my blog to colour code my code. I'm too lazy to go back though all my posts and add the name attribute and the "coldfusion" class to every pre tag, so I thought I'd use jQuery to do it for me. That was easy enough.

$(function(){
  $('pre').attr('name', 'code').addClass('coldfusion');
});

That works a treat for my ColdFusion code, but what if I want to specify javascript highlighting instead? By using the not selector, I can filter out all pre tags that have already have a class so that I only add the coldfusion class to pre tags without a class.

$(function(){
  $('pre').attr('name', 'code').not('[class]').addClass('coldfusion');
});

2 comments

  1. That's not a not selector, it's a not method - Here's how to do it with selectors:
    $('pre[@name=code]:not([@class])').addClass('coldfusion')

    Comment by Peter Boughton – September 19, 2008
  2. Hi Peter, yeah, you're right I'm using the method not the selector. Well spotted! Thanks for posting the selector version.

    Comment by John Whish – September 19, 2008

Leave a comment

If you found this post useful, interesting or just plain wrong, let me know - I like feedback :)

Please note: If you haven't commented before, then your comments will be moderated before they are displayed.