HTML은 수정할 수 없지만 div를 클릭 가능하게 만들어야 할 때가 있습니다. 자바스크립트로 하는 방법을 소개합니다. jQuery는 필요 없습니다.
<script>
document.addEventListener("DOMContentLoaded", function () {
document.querySelectorAll(".YOUR-CLASS-NAME").forEach(function (box) {
// Skip boxes that already contain a link or form control (no nested links)
if (box.querySelector("a, button, input, select, textarea")) return;
var link = document.createElement("a");
link.href = "YOUR-URL-LINK";
while (box.firstChild) link.appendChild(box.firstChild);
box.appendChild(link);
});
});
</script>
.YOUR-CLASS-NAME는 내 div의 클래스로, "YOUR-URL-LINK"는 이동할 링크로 바꾸세요. 스크립트는 페이지가 로드될 때까지 기다린 뒤 div의 내용을 실제 링크 안으로 옮깁니다. 그래서 키보드, 가운데 클릭, “새 탭에서 열기”도 모두 동작합니다. 이미 링크나 입력 필드가 들어 있는 상자는 건너뜁니다. 링크 안에 링크를 넣을 수 없기 때문입니다.
워드프레스에서 jQuery 사용하기
워드프레스는 jQuery를 “no-conflict” 모드로 불러오기 때문에 기본적으로 $ 단축키를 쓸 수 없습니다. jQuery를 쓰고 싶다면 jQuery(function ($) { … })를 사용하세요. 페이지가 준비되면 실행되며, 그 안에서는 $를 쓸 수 있습니다.
<script>
jQuery(function ($) {
$(".YOUR-CLASS-NAME").each(function () {
// Skip boxes that already contain a link or form control (no nested links)
if ($(this).find("a, button, input, select, textarea").length) return;
$(this).contents().wrapAll('<a href="YOUR-URL-LINK"></a>');
});
});
</script>
꽤 간단하죠? 물론 HTML을 수정할 수 있다면, 내용을 직접 <a> 태그로 감싸는 것이 여전히 가장 좋은 방법입니다.
