I was goofing around and trying some regular expressions for the sake of experimenting and I was doing it on the console at bestbuy.com. Suddenly I decided to make things a bit more sophisticated and then the trouble started. My code is supposed to add a button that will highlight the found matches for the regex in question if that button does not exists in the site already, but it’s not working, you can test is at best buy yourselves. Here it is:
var rExpIni = /^\b(?:[A-Z][^aeiou\d\s][a-z]{2})\b\s\b(?:[A-Z][a-z]{2}|[a-z]{3})\b/gm;
var rExp = /\b(?:[A-Z][^aeiou\d\s][a-z]{2})\b\s\b(?:[A-Z][a-z]{2}|[a-z]{3})\b/gm;
function sim(){
$("p, a, span, em, i, strong, b, h1, h2, h3, td, th, hr").each(function(){
if( rExpIni.test($(this).text()) == true){
$(this).css({
"background-color":"#DDBB22",
"border-style":"outset",
"border-width":"3px",
"border-color":"#DDBB22",
"font-size":"12pt",
"font-weight":"bold",
"color":"red"
});
}
});
$("img").each(function(){
if( rExp.test($(this).attr("title")) == true || rExp.test($(this).attr("alt")) == true ){
$(this).css({
"border-style":"inset",
"border-width":"10px",
"border-color":"#DDBB22",
"font-size":"12pt",
"font-weight":"bold",
"color":"red"
});
}
});
}
function nao() {
$("p, a, span, em, i, strong, b, h1, h2, h3, td, th, hr, img").each(function(){
$(this).css({
"background-color":"",
"border-style":"",
"border-width":"",
"border-color":"",
"font-size":"",
"font-weight":"",
"color":""
});
});
}
$(document).ready(function(){
if($("body:not(body:has(button#but))")){
var nBotao = $("<button id=\"but\">Procurar</button>");
$("body").prepend(nBotao);
}
});
$("#but").toggle(sim(),nao());
You can use the jQuery object’s
lengthproperty:Also as you are generating the element dynamically you should delegate the event:
Please note that
toggle()method isdeprecatedand you should put all the codes inside the$(document).ready();