JAVASCRIPT&JQUERY
jQuery / Method / .attr() - 속성(attribute)의 값을 가져오거나 속성을 추가하는 메서드
예나부기
2021. 8. 20. 09:28
.attr()
.attr()은 요소(element)의 속성(attribute)의 값을 가져오거나 속성을 추가합니다.
문법 1
.attr( attributeName )
선택한 요소의 속성의 값을 가져옵니다. 예를 들어
$( 'div' ).attr( 'class' );
는 div 요소의 class 속성의 값을 가져옵니다.
문법 2
.attr( attributeName, value )
선택한 요소에 속성을 추가합니다. 예를 들어
$( 'h1' ).attr( 'title', 'Hello' );
는 h1 요소에 title 속성을 추가하고 속성의 값은 Hello로 합니다.
예제 1
h1 요소의 class 속성의 값을 가져와서 출력합니다.
<!doctype html>
<html lang="ko">
<head>
<meta charset="utf-8">
<title>jQuery</title>
<script src="//code.jquery.com/jquery-3.3.1.min.js">
</script>
<script>
$( document ).ready( function() {
var hClass = $( 'h1' ).attr( 'class' );
$( 'span' ).text( hClass );
} );
</script>
</head>
<body>
<h1 class="hello">Lorem ipsum dolor.</h1>
<p>h1 class value is : <span></span></p>
</body>
</html>
예제 2
input 요소에 Input your address를 값으로 하는 placeholder 속성을 추가합니다.
<!doctype html>
<html lang="ko">
<head> <meta charset="utf-8">
<title>jQuery</title>
<style> input { font-size: 30px; } </style>
<script src="//code.jquery.com/jquery-3.3.1.min.js"></script>
<script>
$( document ).ready( function() {
$( 'input' ).attr( 'placeholder', 'Input your address'
);
} );
</script>
</head>
<body>
<input type="text">
</body>
</html>
참고
- 속성(attribute)을 제거하고 싶다면 .removeAttr()을 사용합니다.
- 선택한 요소의 css 속성값을 가져오거나 style 속성을 추가할 때는 .css()를 사용합니다.
- .prop()는 자바스크립트 입장에서의 속성값을 가져오거나 추가합니다.