Giant Danio Fish
본문 바로가기
jQuery

jQuery - 속성 메서드

by 코딩왕자 2022. 9. 3.

jQuery 속성 관련 메서드

jQuery 속성 관련 메서드에 대해 알려드리겠습니다.


attr() 메서드

선택한 요소의 attribute(속성)를 선택, 생성, 변경할 수 있습니다.

실행 분류 형식
취득 $("a").attr("href");
생성, 변경 $("a").attr("href", "http://icoxpublish.com").attr("target", "_blank");
$("a").attr({"href": "http://icoxpublish.com", target:"_blank"});
콜백 함수 $("a").attr("href", function(index, h){
    //index는 각 a 요소의 index 0, 1, 2
    //h는 각 a 요소 href 속성
    return attribute(속성) // 각 a 요소의 속성을 생성 및 변경합니다.
});
...
<a href="http://www.daum.net" target="_blank" title="새창">다음</a>
<a href="http://www.daum.net" target="_blank" title="새창">네이버</a>
<a href="http://www.daum.net" target="_blank" title="새창">네이트</a>

prop() 메서드

attr()가 html attribute(속성)에 관련된 메서드라면 prop()는 자바스크립트 property(프로퍼티)에 관련된 메서드입니다. prop() 메서드는 요소의 속성을 true, false로 제어할 수 있습니다.

<input type="checkbox" id="html"><label for="html">html</label>
<input type="checkbox" id="css"><label for="css">css</label>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script>
    $(document).ready(function() {
        console.log($("input:checkbox").eq(0).attr("checked"));
        console.log($("input:checkbox").eq(1).prop("checked"));
        $("input:checkbox").eq(0).attr("checked", "checked");
        $("input:checkbox").eq(1).prop("checked", true);
        console.log($("input:checkbox").eq(0).attr("checked"));
        console.log($("input:checkbox").eq(1).prop("checked"));
    });
</script>
결과

'jQuery' 카테고리의 다른 글

jQuery - 스타일 메서드  (4) 2022.09.03
jQuery - 클래스 메서드  (6) 2022.09.03
jQuery - 탐색 선택자  (12) 2022.08.30
jQuery - 필터 선택자  (8) 2022.08.30
jQuery - 속성 선택자  (7) 2022.08.30

댓글


광고 준비중입니다