728x90
D3를 사용하여 DOM 요소 선택하기
- D3를 사용하면 HTML에서 DOM 요소를 조작할 수 있음
- 먼저 특정 요소 또는 요소 그룹을 선택한 뒤, 다양한 D3 메서드를 사용하여 해당요소를 조작해야함
- D3.js 내 메소드를 사용하여 DOM 요소를 선택하는 방법
DOM 선택
- DOM 요소의 참조 가져오기
- d3.select(css-selector)
- 지정된 css-selector를 기반으로 HTML에서 일치하는 첫번째 요소를 반환
- d3.selectAll(css-selector)
- 지정된 css-selector를 기반으로 HTML에서 일치하는 모든 요소를 반환
d3.select()
지정된 css-selector를 기반으로 HTML에서 일치하는 첫번째 요소를 반환
<!doctype html>
<html>
<head>
<script src="https://d3js.org/d3.v4.min.js"></script>
</head>
<body>
<p>1번째 요소</p>
<p>2번째 요소</p>
<script>
d3.select("p").style("color", "green");
</script>
</body>
</html>
<!doctype html>
<html>
<head>
<script src="https://d3js.org/d3.v4.min.js"></script>
</head>
<body>
<p id="p1">1번째 요소</p>
<p id="p2">2번째 요소</p>
<script>
d3.select("#p2").style("color", "green");
</script>
</body>
</html>
d3.selectAll()
- 지정된 css-selector를 기반으로 HTML에서 일치하는 모든 요소를 반환
<!doctype html>
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8"/>
<script src="https://d3js.org/d3.v4.min.js"></script>
</head>
<body>
<p>1번째 요소</p>
<p>2번째 요소</p>
<script>
d3.selectAll("p").style("color", "blue");
</script>
</body>
</html>
- selectAll도 마찬가지로 class 또는 id를 이용하면 이름으로 모든 요소를 선택할 수 있다.
<!doctype html>
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8"/>
<script src="https://d3js.org/d3.v4.min.js"></script>
<style>
.myclass{
color:red
}
</style>
</head>
<body>
<p class="myclass ">1번째 요소</p>
<p>2번째 요소</p>
<p class="myclass ">3번째 요소</p>
<script>
d3.selectAll(".myclass ").style('color','blue');
</script>
</body>
</html>
d3.select() 및 d3.selectAll() 를 사용하여 지정된 기준에 따라 일치하는 DOM요소를 선택할 수 있다.
이전 게시물은 아래 링크로 !
'Dev > D3' 카테고리의 다른 글
[D3.js] D3(Data Driven Document)시작하기 (0) | 2021.06.22 |
---|