patternjavascriptMinor
Checking a HTML element's class
Viewed 0 times
elementcheckingclasshtml
Problem
$('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($("Run example").click(function() {
run(code);
}));I noticed if I didn't have
if (!c) { then the loop could abrubtly halt if it found a `` 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".
Solution
What about this?
http://jsfiddle.net/mfJMb/
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($("Run example").click(function(){
alert( $t.text() );
}));
}
});Code Snippets
$('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() );
}));
}
});Context
StackExchange Code Review Q#7517, answer score: 2
Revisions (0)
No revisions yet.