728x90
.attr()
.attr()은 요소(element)의 속성(attribute)의 값을 가져오거나 속성을 추가한다.
문법 1 - 속성의 값 가져오기
- 선택한 요소의 속성의 값을 가져온다.
.attr( attributeName )
- 예를 들어 아래는 div 요소의 class 속성의 값을 가져온다.
$( 'div' ).attr( 'class' );
문법 2 - 속성 추가하기
- 선택한 요소에 속성을 추가한다.
.attr( attributeName, value )
- 예를 들어 아래는 h1 요소에 title 속성을 추가하고 속성의 값은 Hello로 한다.
$( 'h1' ).attr( '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()는 자바스크립트 입장에서의 속성값을 가져오거나 추가한다.
참고 : https://www.codingfactory.net/10208
jQuery / Method / .attr() - 속성(attribute)의 값을 가져오거나 속성을 추가하는 메서드
.attr() .attr()은 요소(element)의 속성(attribute)의 값을 가져오거나 속성을 추가한다. 문법 1 - 속성의 값 가져오기 선택한 요소의 속성의 값을 가져온다. .attr( attributeName ) 예를 들어 아래는 div 요소
www.codingfactory.net
728x90
'jQuery' 카테고리의 다른 글
addClass(), removeClass(), hasClass() 예제 (0) | 2022.12.24 |
---|---|
상위 요소 선택자(parents(), parents("요소 선택") (0) | 2022.12.05 |
jQuery 선택자 모음 (0) | 2022.12.05 |
jquery 비 동기 통신 $.ajax(), $.get(), $.post() 사용방법 (0) | 2022.12.01 |
jQuery - select박스 선택된 값 가져오기 (0) | 2022.11.25 |