JSFiddle - React, Tailwind, and code Playground

by tirams

HTML

<button class=showA onClick="showA()">
    Show A
</button>

<button class=showB onClick="showB()">
    Show B
</button>

<div class=parentToBoth>
    <div class=A>
        this is the A div
        <p>
            Some more text in A a is wider
        </p>
    </div>

    <div class=B>
        this is the B div
        <p>
           Here Bs content
        </p>
        <p>
           bottom is longer
        </p>
    </div>

</div>

CSS

.parentToBoth {
    position: relative;
    max-height: 400px;
    margin-top: 50px;
}

.A {
    position: absolute;
    top: 0;
    left: 0;
    z-index: 100;
    background-color: pink;
}

.B {
    position: absolute;
    top: 0;
    left: 0;
    z-inde: 90;
    background-color: yellow;
}

JavaScript

function setTopBottom(top, bottom) {
    if (top) {
        top.setAttribute("style", "z-index: 100");
    }
    if (bottom) {
        bottom.setAttribute("style", "z-index: 50");
    }
}

function getDivs() {
    let A = document.getElementsByClassName('A');
    let B = document.getElementsByClassName('B');
    return {
        A: A[0],
        B: B[0]
    }
}

function showA() {
    let elements = getDivs();
    setTopBottom(elements.A, elements.B);
}

function showB() {
    let elements = getDivs();
    setTopBottom(elements.B, elements.A);
}