4
\$\begingroup\$
$('pre').each(function(index) {
    var c = $(this).attr("class");
    if (!c) {
        return true;
    }
    // Match only Javascript code snippets
    if (!c.match(/brush: js; class-name: 'jsbox'/)) {
        return true;
    }
    var code = $(this).text();
    $(this).after($("<button>Run example</button>").click(function() {
        run(code);
    }));

I noticed if I didn't have if (!c) { then the loop could abrubtly halt if it found a <pre> element without a class.

I wonder how to write this more succinctly. I'm also wondering about my matching options, since I've noticed different ways people match / compare strings in Javascript and I wondered what was "de rigueur".

\$\endgroup\$
2
+50
\$\begingroup\$

It looks like whatever library you're using is generating properties and sticking them inside the class attribute, which I've never seen before and seems questionable (why can't they be attributes on the element?). Because they look generated, could you maybe end up with something like this:

<pre class="class-name: 'jsbox'; brush: js">

or this:

<pre class="brush: js; [another property]; class-name: 'jsbox'">

If so, then you may want to only look for one property (like brush: js) to determine if you're looking at a JS code snippet.

It's fine to use String.match() for finding a substring but realize that String.indexOf() is preferable if you have no need for regex: https://stackoverflow.com/a/4757501/1100355

So you would end up with something like this:

var c = $(this).attr("class");
if (!c || c.indexOf('brush: js') < 0) {
  return true;
}

...
\$\endgroup\$
2
\$\begingroup\$

Change

var code = $(this).text();   

to

var code = $(this).val();
\$\endgroup\$
  • \$\begingroup\$ That's not the problem. The problem is that I want to compress the '!c' lines. \$\endgroup\$ – Kai Hendry Jan 9 '12 at 8:08
2
\$\begingroup\$

What about this?

http://jsfiddle.net/mfJMb/

$('pre').each(function(){
  var $t = $(this);

  // Match only Javascript code snippets
  if( ( $t.attr("class") || '') .match(/brush: js; class-name: 'jsbox'/) ){
    $t.after($("<button>Run example</button>").click(function(){
        alert( $t.text() );
    }));
  }
});
\$\endgroup\$
  • \$\begingroup\$ I like this answer, but you should have copied in the "TidyUp" version since I find the $t variable name, unconventional. \$\endgroup\$ – Kai Hendry Jan 11 '12 at 9:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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