JaSon JaSon - 4 months ago 9
jQuery Question

Search terms separated from rest of the code?

$("[title*='A-title-im-not-interested-in']").closest("div.parentdivofproduct").attr("style","visibility: hidden !important; display: none !important;");
$("[title*='Second-title-no-need']").closest("div.parentdivofproduct").attr("style","visibility: hidden !important; display: none !important;");
$("[title*='Third-i-dont-want-to-see']").closest("div.parentdivofproduct").attr("style","visibility: hidden !important; display: none !important;");
$("[title*='4thtitle']").closest("div.parentdivofproduct").attr("style","visibility: hidden !important; display: none !important;");


I'm using the above code to hide the titles I don't want. Each is in a separate line, with all of the stuff repeating what needs to be done when there is a match.
Is there a way to achieve the same result where I could list my titles to one place, and keep the what-to-do code separated? Something like this?

$("[title*=MYTITLES]").closest("div.parentdivofproduct").attr("style","visibility: hidden !important; display: none !important;");
MYTITLES {'A-title-im-not-interested-in','Second-title-no-need','Third-i-dont-want-to-see','4thtitle'};

Answer

Could try something like

var titles = ['title 1', 'title 2', 'title 3'];

$("[title]").filter(function(){
   return titles.indexOf(this.title) >-1;
}).closest("div.parentdivofproduct").attr("style","visibility: hidden !important; display: none !important;");

Or

$.each(titles, function(_, title){
    $('[title="' + title + '"]').closest("div.parentdivofproduct").attr...
}) 

Or

var selector = titles.map(function(title){
     return '[title="' + title + '"]';
}).join()
$(selector).closest("div.parentdivofproduct").attr...
Comments