javascript

[Javascript] querySelectorAll, querySelector, 여러개의 동일한 클래스명내에 특정한 태그내 text값 얻기

http://portfolio.wonpaper.net 2024. 4. 4. 06:55

[ html ]

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
<div class="tourist">
    <div class="ct1">
    <h1>
        대표 관광명소
    </h1>
    <div class="grid">
 
        <a href="javascript:;" class="box">
        <img src="/pds/tour/aaaa.jpg" alt="">
        <div class="tit">
            <h1>
            aaaa.jpg
            </h1>
            <div class="bar">
            </div>
        </div>
         <div class="box_num" style="display:none;">1</div>
        </a>
 
 
        <a href="javascript:;" class="box">
        <img src="/pds/tour/bbbb.jpg" alt="">
        <div class="tit">
            <h1>
            bbbb.jpg
            </h1>
            <div class="bar">
            </div>
        </div>
         <div class="box_num" style="display:none;">2</div>
        </a>
    </div>
   </div>
</div>
cs

 

 

[  javascript ]

 

1
2
3
4
5
6
7
8
document.querySelectorAll('.tourist .box').forEach(function (box) {
    box.addEventListener('click'function () {
    
        var boxNum = this.querySelector('.box_num').innerText;
        alert(boxNum);
 
    });
});
cs

 

 

document.querySelectorAll('.tourist .box').forEach 돌려서, 

this.querySelector('.box_num').innerText 로 해당 값을 받아온다.