How to pick up middle item with javascript or css?

Asked

Viewed 186 times

1

Guys, I have the following situation:

<div class="corpo">
   <div class="item"></div>
   <div class="item"></div>
   <div class="item"></div>
</div>

This Divs block is randomly generated and I can’t add anything else to it. I want to find a way to know which "item" is in the middle, with javascript or css. Like in the middle I want an orange edge and on both sides I want a green edge. Someone has a solution?

3 answers

2


You can use js using the method getElementsByClassName

<div class="corpo">
   <div class="item">1</div>
   <div class="item">2</div>
   <div class="item">3</div>
</div>
<script>
var item = document.getElementsByClassName('item');	
alert(item[1].textContent);
</script>

This method will store all occurrences in an array, and you can access it by the numeric key.

1

If the div has only 3 items, it can be done like this:

    .item{
        border: 1px solid green;
    }
    
    .item:nth-child(even) {
        border-color: orange;
    }
    <div class="corpo">
       <div class="item">1</div>
       <div class="item">2</div>
       <div class="item">3</div>
    </div>
    

0

You can use this way too, if there is more than one element in the center that requires orange edge:

.corpo .item:first-child,
.corpo .item:last-child {
  border: 1px solid green;
}
        
.item {
    border: 1px solid orange;
}
<div class="corpo">
   <div class="item">Testo 1</div>
   <div class="item">Testo 2</div>
   <div class="item">Testo 3</div>
   <div class="item">Testo 4</div>
</div>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.