웹 개발을 하다 보면 앵커(<a>) 태그에 설정된 URL, 즉 href 속성의 값을 자바스크립트로 가져와야 하는 경우가 종종 있습니다. 이번 글에서는 jQuery의 attr() 메서드를 활용해 href 값을 간단하게 추출하는 방법을 예제와 함께 살펴보겠습니다.
예제 마크업
다음과 같은 앵커 태그가 있다고 가정해 보겠습니다.
<a class="demo" title="get the url" href="./mainPage.jsp/1245">href value at console</a>
여기서 필요한 것은 링크 텍스트가 아니라 오직 URL 값, 즉 href 속성의 값입니다. 이를 얻으려면 attr() 메서드를 사용하면 됩니다.
attr('href')
전체 예제 코드
아래는 위 내용을 실제로 구현한 전체 코드입니다.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<body>
<ul class="getURLDemo">
<li>
<a class="demo" title="get the url" href="./mainPage.jsp/1245">href value at console</a>
</li>
</ul>
</body>
<script>
var hrefValue = $('ul.getURLDemo li a.demo').attr('href');
console.log(hrefValue);
</script>
</html>
실행 방법
위 프로그램을 실행하려면 파일 이름을 “anyName.html”(index.html)로 저장한 뒤, VSCode 편집기에서 해당 파일을 마우스 오른쪽 버튼으로 클릭하고 “Open with Live Server” 옵션을 선택하면 됩니다.
실행 결과
코드를 실행하면 브라우저 화면에는 다음과 같은 목록이 표시됩니다.

개발자 도구 콘솔(Console)을 열어 보면 href 속성 값인 ./mainPage.jsp/1245가 정상적으로 출력되는 것을 확인할 수 있습니다.

참고: 순수 자바스크립트로 가져오기
jQuery를 사용하지 않고도 순수 자바스크립트(바닐라 JS)만으로 동일한 결과를 얻을 수 있습니다. querySelector()로 요소를 선택한 후 getAttribute() 메서드를 호출하면 됩니다.
const hrefValue = document.querySelector('ul.getURLDemo li a.demo').getAttribute('href');
console.log(hrefValue); // ./mainPage.jsp/1245
또한 최신 브라우저 환경이라면 a.href 프로퍼티를 사용해 절대 경로 형태의 전체 URL을 얻을 수도 있으며, 상대 경로 그대로가 필요하다면 getAttribute('href')를 사용하는 것이 좋습니다.