HOWTO · jQuery
jQuery 클래스 가져오기
이 튜토리얼은 jQuery에서 클래스 이름을 가져오는 방법을 보여줍니다.
이 페이지의 내용
이 튜토리얼은 jQuery에서 클래스 이름을 가져오는 방법을 보여줍니다.
jQuery 클래스 가져오기
attr() 메소드는 jQuery에서 클래스 이름을 가져올 수 있습니다. 이 메서드 외에도 hasClass() 메서드를 사용하여 특정 요소에 특정 클래스 이름이 있는지 확인할 수 있습니다.
두 가지 방법에 대한 예를 설명하고 보여드리겠습니다.
attr() 메소드는 HTML 요소 속성의 값을 가져오는 데 사용됩니다. attr() 메소드의 클래스 이름을 매개변수로 사용하여 클래스 이름을 가져올 수 있습니다.
attr 메서드를 사용하여 클래스 이름을 가져오는 구문은 다음과 같습니다.
attr('class')
이 방법의 예를 시도해 보겠습니다.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery Get Class Name</title>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
var Name = $("#DELFTSTACK").attr("class");
alert(Name);
});
});
</script>
</head>
<body>
<div id="DELFTSTACK" class="Delfstack">Click the button to get the class name for this element.</div>
<button type="button">Click Here</button>
</body>
</html>
위의 코드는 주어진 요소의 클래스 이름을 경고합니다. 출력 참조:
클래스가 attr() 메소드에서 얻은 이름을 가지고 있는지 확인합시다. 이를 위해 hasClass() 메소드를 사용할 수 있습니다.
예를 참조하십시오.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery Get Class Name</title>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
var Name = $("#DELFTSTACK").attr("class");
if ($( "#DELFTSTACK" ).hasClass( Name )){
alert(Name);
}
});
});
</script>
</head>
<body>
<div id="DELFTSTACK" class="Delfstack">Click the button to get the class name for this element.</div>
<button type="button">Click Here</button>
</body>
</html>
위의 코드는 attr 메소드가 올바른 클래스 이름을 반환하고 hasClass가 true를 반환하기 때문에 유사한 출력을 갖게 됩니다. 출력 참조: