개요
HTML 문서에서 특정 div 영역 안에 있는 여러 개의 텍스트 요소(span 등)를 다른 요소의 텍스트 값으로 한 번에 교체하고 싶다면, JavaScript의 document.querySelectorAll()과 getElementsByClassName() 메서드를 함께 활용하면 간단하게 해결할 수 있습니다.
querySelectorAll()은 CSS 선택자와 일치하는 모든 요소를 NodeList 형태로 반환하며, getElementsByClassName()은 지정한 클래스 이름을 가진 요소들을 가져옵니다. 이 두 가지를 조합하면 기준이 되는 텍스트 값을 읽어온 뒤, 대상 span 요소들에 일괄 적용할 수 있습니다.
예제 코드
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initialscale=1.0">
<title>Document</title>
<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>
</head>
<body>
<h2 class="uniqueId"> My Name is John </h6>
<div class="my-main-div-class">
<div class="div-class-2">
<span>My h6 value must be here...</span>
</div>
<div class="div-class-end">
<span>My h6 value must be here...</span>
<span>My h6 value must be here...</span>
</div>
</div>
<script>
const allSpan = document.querySelectorAll('.my-main-div-class span'),
repaceAboveText =
document.getElementsByClassName('uniqueId')[0].textContent;
for (var newElement of allSpan){
newElement.textContent=repaceAboveText
}
</script>
</body>
</html>코드 설명
위 코드의 핵심 로직은 다음과 같습니다.
1. 대상 요소 선택: document.querySelectorAll('.my-main-div-class span')을 사용하여 my-main-div-class 클래스를 가진 div 내부의 모든 span 요소를 선택합니다.
2. 교체할 텍스트 가져오기: document.getElementsByClassName('uniqueId')[0].textContent를 통해 uniqueId 클래스를 가진 h2 요소의 텍스트 내용을 읽어옵니다.
3. 텍스트 일괄 교체: for...of 반복문으로 선택된 모든 span 요소를 순회하면서, 각 요소의 textContent를 앞서 읽어온 텍스트로 덮어씁니다. 그 결과 페이지가 로드되면 모든 span의 내용이 'My Name is John'으로 변경됩니다.
실행 방법
위 프로그램을 실행하려면 파일 이름을 'anyName.html'(예: index.html)로 저장한 뒤, 해당 파일에서 마우스 오른쪽 버튼을 클릭합니다. 이후 VS Code 편집기에서 'Open with Live Server' 옵션을 선택하면 브라우저에서 결과를 바로 확인할 수 있습니다.
실행 결과
프로그램을 실행하면 다음과 같은 출력 결과를 얻을 수 있습니다.
