How can I select an element with specific attributes only?

837 views Asked by At

I need to paste src to image depending on color choice.

Here is my markup:

<div data-img="[black-blue.png]" black blue></div>
<div data-img="[black.png]"  black></div>
<div data-img="[blue.png]"  blue></div>
<div data-img="[orange.png]"  orange></div>
<div data-img="[black-blue-orange.png]" black blue orange></div>
<div data-img="[blue-orange.png]" blue orange></div>
<div data-img="[blue-red-orange.png]" blue red orange></div>

My script works on elements attributes:

var attributes = '';
for(var i = 0; i<activeColorsArray.length; i++ ){
   attributes += '['+activeColorsArray[i]+']';
}

Output: [blue][black], for examples. It's works for black&blue item, but it's catch black&blue&orange element too.

[blue][black]:not([orange]) not working for me because I have 8 colors...

Need something like ONLY THIS selector.

2

There are 2 answers

0
Temani Afif On

One idea is to consider the number of attributes an element has. If you want to target only blue and black then you target the elements with only 3 attributes (including data-img in your case)

activeColorsArray= ['blue','black'];

var attributes = '';
for(var i = 0; i<activeColorsArray.length; i++ ){
   attributes += '['+activeColorsArray[i]+']';
}

var elements = document.querySelectorAll(attributes);
var items = Array.from(elements);

elements = items.filter((e) => {
 return e.attributes.length == 3;
})

for(var i=0;i<elements.length;i++) {
  elements[i].style.color="red";
}
<div data-img="[black-blue.png]" black blue>black blue</div>
<div data-img="[black.png]"  black>black</div>
<div data-img="[blue.png]"  blue>blue</div>
<div data-img="[orange.png]"  orange>orange</div>
<div data-img="[black-blue-orange.png]" black blue orange>black blue orange</div>
<div data-img="[blue-orange.png]" blue orange>blue orange</div>
<div data-img="[blue-red-orange.png]" blue red orange>blue red orange</div>

1
TylerH On

If that's your exact markup, the CSS attribute selector would work without any JavaScript. This code will match only divs with the data-img attribute with a value of exactly [black-blue.png]. Trying to select by naked attributes (div[black][blue] {}) is not recommended for the exact reason you've described.

div[data-img="[black-blue.png]"] {
    color: red;
}
<div data-img="[black-blue.png]" black blue>black blue</div>
<div data-img="[black.png]"  black>black</div>
<div data-img="[blue.png]"  blue>blue</div>
<div data-img="[orange.png]"  orange>orange</div>
<div data-img="[black-blue-orange.png]" black blue orange>black blue orange</div>
<div data-img="[blue-orange.png]" blue orange>blue orange</div>
<div data-img="[blue-red-orange.png]" blue red orange>blue red orange</div>

https://jsfiddle.net/nk98tch1/