I have a jQuery code wich is counting some divs where certain Breakfast board are found as below
var board_bb1 = $('div[data-board="Bed And Breakfast"]').length;
var board_bb2 = $('div[data-board="Breakfast"]').length;
var board_bb3 = $('div[data-board="Breakfast Buffet"]').length;
var board_bb4 = $('div[data-board="Breakfast (Full Breakfast)"]').length;
var board_bb5 = $('div[data-board="Continental Breakfast"]').length;
var board_bb8 = $('div[data-board="Bed and Breakfast"]').length;
var board_bb6 = $('div[data-board="Full Breakfast"]').length;
var board_bb7 = $('div[data-board="Breakfast (Continental Breakfast)"]').length;
var board_bb = board_bb1 + board_bb2 + board_bb3 + board_bb4 + board_bb5 + board_bb6 + board_bb7 + board_bb8;
The attributes from data-board are coming from an API service, and sometimes is breakfast sometimes is Breakfast, bed And Breakfast etc. Is there a way to simply the above code to count all the divs who has the word Breakfast in data-board
$("div[data-board*='Breakfast']").length
The *= part will look for any attribute containing the word breakfast.
IF you are not using jQuery in your project, in modern browsers this will work to:
document.querySelectorAll("div[data-board*='Breakfast']").length;
To complete it: a cross-browser solution that will work all the way back to IE5.5
var allDivs = document.getElementsByTagName("div");
var count = 0;
for (var i = 0, i < allDivs.length; i++)
{
if (allDivs[i].getAttribute("data-board") && allDivs[i].getAttribute("data-board").match(/Breakfast/) )
{
count++;
}
}
After this count will return the amount of divs containing the word Breakfast in the data-board attribute
You can use ~ operator
$("div[data-board~='Breakfast']").length
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With