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



Suppose

<div myattr='user1'>abcd</div>
<div myattr='user2'>1234</div>
<div myattr='user2'>wxyz</div>
<div myattr='user3'>7890</div>

For now third element’s display must be none.

I tried

div[myattr='user2'] ~ div[myattr='user2'] {
    display: none;
}

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.

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:

for (const entry of document.querySelectorAll("[data-myattr]")) {
    const next = entry.nextElementSibling;
    if (next.getAttribute("data-myattr") === entry.getAttribute("data-myattr")) {
        entry.classList.add("hidden");
    }
}

Live Example:

const display = document.getElementById("display");
display.textContent = "Before";
setTimeout(() => {
    for (const entry of document.querySelectorAll("[data-myattr]")) {
        const next = entry.nextElementSibling;
        if (next.getAttribute("data-myattr") === entry.getAttribute("data-myattr")) {
            entry.classList.add("hidden");
        }
    }
    display.textContent = "After";
}, 1000);
.hidden {
    display: none;
}
<div id="display"></div>
<hr>
<div data-myattr='user1'>first user1</div>
<div data-myattr='user2'>first user2</div>
<div data-myattr='user2'>second user2</div>
<div data-myattr='user3'>first user3</div>
<hr>
<div data-myattr='user1'>first user1</div>
<div data-myattr='user2'>first user2</div>
<div data-myattr='user3'>first user3</div>
<div data-myattr='user3'>second user3</div>
<div data-myattr='user3'>third user3</div>
<hr>
<div data-myattr='user1'>first user1</div>
<div data-myattr='user2'>first user2</div>
<div data-myattr='user3'>first user3</div>
<div data-myattr='user2'>second user2 but not in a row</div>
<div data-myattr='user3'>second user3 but not in a row</div>

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



Source: stackoverflow