본문 바로가기
JavaScript

jQuery - 속성 메서드

by 코딩 냠냠 2022. 9. 4.
728x90
반응형

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("herf", function(index, h) {
    //index는 각 a 요소의 index 0, 1, 2
    //h는 각 a 요소 href 속성
return attribute(속성) // 각 a 요소의 속성을 생성 및 변경합니다.
});
....
<a href="http://www.daum.net" targe="_blank" title="새창">다음</a>
<a href="http://www.naver.com" targe="_blank" title="새창">네이버</a>
<a href="http://www.nate.net" targe="_blank" title="새창">네이트</a>

예제

jQuery

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
    $(document).ready(function(){
        console.log($("#site > a:eq(0)").attr("href"));
        $("#site > a:eq(1)").attr("href", "http://m.naver.com").text("네이버 모바일");
        $("#site a").attr("title", function(){
            return "새창";
        });
    });
</script>

결과

prop() 메서드

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

예제 - jQuery

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/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>

결과

attr()메서드는 checked 속성이 요소에 추가되는 반면 prop()메서드의 true는 자바스크립트의 프로퍼티로 처리됩니다.

'JavaScript' 카테고리의 다른 글

mouseover / mouseenter  (2) 2022.09.05
jQuery - 스타일 메서드  (4) 2022.09.04
jQuery - 클래스 메서드  (2) 2022.09.03
요소 크기 메서드  (4) 2022.09.01
jQuery - 탐색 선택자  (4) 2022.08.31

댓글


자바스크립트

Javascript

자세히 보기
html
css
광고 준비중입니다.
<