Skip to content
Advertisement

Set some styles if an element is followed by an element with same attribute

Suppose

JavaScript

For now third element’s display must be none.

I tried

JavaScript

But this code only works for element whose myattr is user2 not for other users / attribute values and this sets display of third element to none instead of second.

I want to set some styles to every element whose next element have same attribute.

How can I achieve this?

CSS code is preferred but JavaScript can also work here.

Advertisement

Answer

Because you want to refer back to the earlier element’s attribute value, I don’t think you can do this with CSS. It’s fairly straightforward with JavaScript:

JavaScript

Live Example:

JavaScript
JavaScript
JavaScript

Side note: I’ve used data-myattr rather than myattr above because custom attributes should always use the data- prefix.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement