each()
object 와 배열에서 사용할 수 있는 반복 함수
배열, length 속성을 갖는 배열과 유사 배열 객체들을 index를 기준으로 반복한다.
<script>
$(function(){
console.log($('#ul1 li').length); //5
$('#ul1 li').each(function(i,obj){
console.log(`${i} : ${$(obj).html()}`); });
});
</script>
<ul id="ul1">
<li>메뉴1-1</li>
<li>메뉴1-2</li>
<li>메뉴1-3</li>
<li>메뉴1-4</li>
<li>메뉴1-5</li>
</ul>
ul1이라는 id를 가진 것의 li를 선택자로 하여 each를 적용했다.
function(i, obj)에서 i는 선택한 요소의 index 값이고 obj는 그 요소 객체이다.
index 번호와 객체의 html()으로 li 안의 내용을 전부 확인하였다.
<script>
$(function () {
$('#ul1 li').each(function (i) {
console.log(`${i} : ${$(this).html()}`);
});
});
</script>
function(i)로 index번호만 가져올 경우에는 this로 객체를 지정한다.
'WEB > jQuery' 카테고리의 다른 글
자식요소 추가 - append, prepend / 형제요소 추가 - after, before (0) | 2022.06.20 |
---|---|
너비, 높이 - width, height / innerWidth, innerHeight / outerWidth, outerHeight (0) | 2022.06.20 |
jQuery 좌표 : offset() , position() (0) | 2022.06.20 |
val() - attr('value') , html() - text() (0) | 2022.06.20 |
attr('class'), addClass, removeClass, toggleClass, hasClass - 적용된 클래스 조회, 클래스 추가, 클래스 삭제, 클래스 확인 (0) | 2022.06.20 |