.attr
jQuery 객체의 메서드 중 setAttribute, getAttribute에 대응되는 메서드는 attr이다. 또한, removeAttribute에 대응되는 메서드로는 removeAttr이 있다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
<!DOCTYPE html>
<html lang="en">
<head>
<script src="jquery-3.7.1.js"></script>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>attr</title>
</head>
<body>
<a id="target" href="http://opentutorials.org">opentutorials</a><br>
<script>
let a = $('#target').attr('href'); //"http://opentutorials.org"을 리턴
$('#target').attr('title', 'opentutorials.org'); //setAttribute => title 속성의 값을 설정
let b = $('#target').attr('title');
$('#target').removeAttr('title'); //title 속성 제거
let c = $('#target').attr('title');
document.write("a: " + a + "<br>");
document.write("b: " + b + "<br>");
document.write("c: " + c);
</script>
</body>
</html>
|
cs |
.prop
DOM과 마찬가지로 jQuery도 속성(attribute)과 프로퍼티(property)를 구분한다. 속성은 attr, 프로퍼티는 prop 메서드를 사용한다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
<!DOCTYPE html>
<html lang="en">
<head>
<script src="jquery-3.7.1.js"></script>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>attr vs prop</title>
</head>
<body>
<h1><a id="t1" href="1.html">HTML</a></h1>
<input id="t2" type="checkbox" checked="checked" /><br>
<script>
let t1 = $('#t1');
document.write(t1.attr('href') + "<br>"); //1.html
document.write(t1.prop('href') + "<br>"); //http://localhost:5500/1.html
let t2 = $('#t2');
document.write(t2.attr('checked') + "<br>"); //checked
document.write(t2.prop('checked') + "<br>"); //true
</script>
</body>
</html>
|
cs |
HTML에 쓴 속성값을 다루고 싶을 때는 .attr() 함수를 사용하고,
JavaScript의 프로퍼티값을 다루고 싶을 때는 .prop() 함수를 사용하면 된다.
.prop()은 지정한 선택자를 가진 첫 번째 요소의 속성값을 가져오거나 속성값을 추가한다.
문법1 - 속성값 가져오기
.prop(propertyName)
=> propertyName 속성의 값을 가져온다.
t1.prop('href'); //http://localhost:5500/1.html
t2.prop('checked'); //true
문법2 - 속성 추가하기
.prop(propertyName, value)
=> propertyName 속성에 value 값을 추가한다.
$('#t2').prop('checked', false); //프로퍼티값 설정 => 체크박스 체크 해제