다음과 같은 html에서 특정 영역을 클릭했을때 text를 가져오고 싶습니다.
조회수 614회
화면에 다음과 같이 표시되고
target1 target2 target3 target4
이것의 구조는 이렇습니다.
<div>
target1
<span>target2</span>
<span>target3</span>
target4
</div>
이 때 target4를 클릭했을 때
target4라는 text를 가져오고 싶습니다.
어떤 방식으로 접근하면 될까요?
1 답변
-
스텍오버플로우에 답변이 올라와서 공유합니다.
var div = document.querySelector("div"); // get the div wrapper div.childNodes.forEach(function(node) { // loop over the nodes var text = node.textContent; // get the text if (node.nodeName=="#text" && text.trim()!="") { // if text and not empty var span = document.createElement("span"); // wrap in a span span.textContent = node.textContent.trim(); node = div.replaceChild(span,node); } }); div.onclick=function(e) { console.log(e.target.textContent); }
span { color:red }
<div> target1 <span>target2</span> <span>target3</span> target4 </div>
댓글 입력