Mia
Mia

Reputation: 6531

Select element based on applied property

I love the "after" (+) selector, it's good to style things after specific elements. Such as:

.title+div {
    background-color: yellow;
}

would make the background color of the div following the element with .title class, yellow.

However, I need a more dynamic way of selecting things.

How would you express this in css?:

"Make the background color of the visibility:visible element, yellow"

Any direction is appreciated.

Upvotes: 0

Views: 99

Answers (3)

Maryam Sayedi
Maryam Sayedi

Reputation: 21

Well as you know there isn't only one type of selector in CSS. In the link below you can find more complex selector such as Attribute Selector:

div[target]{background-color:yellow}
.firstgroup
{
    height:50px;
    width:50px;
    background-color:lightblue; 
    margin:10px;
}
.secondgroup
{
    height:50px;
    width:50px;
    background-color:lightpink; 
    margin:10px; 
}
<div class="firstgroup" target="a"></div>

<div class="firstgroup"></div>

<div class="secondgroup" target="ab"></div>

<div class="firstgroup"></div>

<div class="secondgroup"></div>

Refrence :Complex Selectors

Upvotes: 2

Zach Saucier
Zach Saucier

Reputation: 26014

You can't select non-inline properties in CSS, so something like div[visibility:visible] wouldn't work unless you explicitly stated the property inside the style attribute for the element.

The best way to select an element like this is to select the class with the styles applied to it (if there is one).

.title + .visible {
    background-color:yellow;
}

If this isn't the case, you should almost always use JavaScript.

Upvotes: 3

David Thomas
David Thomas

Reputation: 253486

This is potentially possible, albeit it's very, very fragile and has some requirements.

First, the visibility:visible must appear in the element's inline style attribute, like so:

<span style="visibility:visible">element text</span>

Second you must know the exact string, if a space is added you'll need to either change selector or account for both/all possibilities.

So, with those provisos, you can implement this selection as follows:

[style*="visibility:visible"] {
  background-color: yellow;
}

[style*="visibility: visible"] {
  border: 1px solid #000;
}
<span style="visibility:visible">element text</span>
<span style="visibility: visible">element text</span>

Now, given those requirements, it's usually far easier to just use JavaScript (or one of its libraries, if you must):

Array.prototype.forEach.call(document.querySelectorAll('span'), function (el, index) {
  if (el.offsetHeight) {
    el.style.backgroundColor = 'yellow';
    el.textContent = el.textContent + ' (' + index + ')';
  }
})
span {
  visibility: visible;
}

.jsAddedClass {
  background-color: yellow;
}

#exception {
  display: none;
}
<span>element text</span>
<span>element text</span>
<span id="exception"></span>

References:

Upvotes: 1

Related Questions