Andrey Shandrov
Andrey Shandrov

Reputation: 457

Combine filters to one with add classes

I have one variable, but two different conditions for the filter with the addition of a class for each. You can somehow combine them, i.e. simplify the code so as not to write twice p.filter(function() { return( .. .test($(this).html())); }).addClass( .. );

var p = $('p:not(.wi-dialog,.wi-chapter)');
p.filter(function() { return ((/^[0-9.]+$/).test($(this).html())); }).addClass("wi-number");
p.filter(function() { return ((/^(END)+$/).test($(this).html())); }).addClass( "wi-end" );

Upvotes: 0

Views: 23

Answers (1)

Gabriele Petrioli
Gabriele Petrioli

Reputation: 195992

Why not do a simple .each ?

var p = $('p:not(.wi-dialog,.wi-chapter)');

p.each(function() {
  const node = $(this);
  const html = node.html();
  const number = /^[0-9.]+$/.test(html);
  const end = /^(END)+$/.test(html);

  node
    .toggleClass('wi-number', number)
    .toggleClass('wi-end', end);
});

Upvotes: 2

Related Questions