I am seeking assistance with a project of mine. To illustrate, I have provided a brief code snippet below.
Let's consider a scenario where we have two sections denoted by the class "box". Inside each box, there are elements containing a heading and specific content. For the purposes of this example, let's focus on the headings.
My objective is to insert elements into the right box that align directly behind the text of the headings. It's crucial to mention that these elements should not be pseudo-elements as certain functions in my project are incompatible with them.
How can I accurately position an element behind the text of another element?
generateNewItems();
function generateNewItems() {
let elements = $(".box#test div");
for (let elem of elements) {
let heading = $(elem).children("h3");
let leftPos = 10; /* HOW? */
let el = $("<div>").addClass("new-item").css({
"left": leftPos,
"top": -3
});
$(elem).append(el);
}
}
.new-item {
position:absolute;
background:red;
height:30px;
width:30px;
}
.box {
width:50%;
background:lightblue;
float:left;
}
.box > div {
position:relative;
}
.box > div > h3 {
background:green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="box">
<div>
<h3>test-one</h3>
</div>
<div>
<h3>test-two</h3>
</div>
</div>
<div class="box" id="test">
<div>
<h3>small-text</h3>
</div>
<div>
<h3>long-sample-text</h3>
</div>
</div>