Jquery에는 유용한 선택자들이 많다.
그 중 "visible" 이라는 선택자가 존재하는데, 아래와같은 코드에서 visible처리가 되어있는 요소만 선택할 수 있는 선택자다.
<div class="box">visible</div>
<div class="box">hidden</div>
<div class="box">hidden</div>
<div class="box">hidden</div>
<div class="box">hidden</div>
<style>
   .box {display: none}
   .box:first-child {display: block;}
</style>
이 선택자 또한 자바스크립트로 어렵지않게 구현이 가능하다.
마크업 구조는 위와 동일하다.
<div class="box">visible</div>
<div class="box">hidden</div>
<div class="box">hidden</div>
<div class="box">hidden</div>
<div class="box">hidden</div>
<style>
   .box {display: none}
   .box:first-child {display: block;}
</style>
// 제이쿼리 :visible과 동일한 기능을 가진 함수
function isVisible(el) {
	return el.offsetWidth > 0 && el.offsetHeight > 0;
}
//visible element 확인
const boxs = document.querySelectorAll(".box"); 
const visibleBox = Array.from(boxs).filter(isVisible);
console.log(visibleBox)
위 코드에서는 box 엘리먼트들을 querySelectorAll()로 선택 한 후 Array.from()으로 배열로 변환하여, Array 메서드인 filter()를 사용해서 visible 처리가 되어있는 box를 걸러내어 visibleBox에 저장한다.
console.log()를 사용하여 찍어보면 visible 처리가 되어있는 요소가 담겨있는것을 확인 할 수 있다.
반응형
    
    
    
  '퍼블리셔 Note > JAVASCRIPT' 카테고리의 다른 글
| [Javascript] Array.filter() 메소드 (0) | 2023.07.28 | 
|---|---|
| [Javascript] 삼항연산자 (0) | 2023.07.26 | 
| [Javascript] 체크박스 전체 선택 기능. (0) | 2023.03.15 | 
| [Javascript] querySelector를 사용하여 active클래스가 있는 index 조회 (0) | 2023.03.06 | 
| [JQuery]갤러리 형태 썸네일 클릭시 해당 index로 팝업 형태 swiper의 index 같은 위치로 옮기기 (0) | 2022.05.20 |