본문 바로가기
IT_Developers/Javascript

jQuery - 이미지의 img src 태그로 선택하기

by 고코더 2019. 4. 12.

jquery img src selector


안녕하세요.
고코더 입니다.


개발을 하던 중에 이미지의 src 속성 
이미지의 주소를 선택하여 수정할 일이 생겼는데
쓸모가 많은 방식인거 같아 
블로그를 남겨드립니다.

제이쿼리에서 img의 src 속성으로 당연히 선택을 할 수 있습니다.
제 블로그에 있는 이미지 주소를 사용해 말씀드리겠습니다.

https://tistory1.daumcdn.net/tistory/2778128/skin/images/epantheo.jpg


▼ 이미지 src를 선택하는 3가지 방법입니다.

1
2
3
4
5
6
7
8
9
10
11
1. 이미지 주소 전체를 넣어 검색
    - 하나의 이미지만 선택할때 유용 합니다.
    ex) $("img[src='https://tistory1.daumcdn.net/tistory/2778128/skin/images/epantheo.jpg']")
2. 이미지 주소 앞 에서부터 매칭.
    - 같은 폴더 기준이나 같은 URL의 이미지만 선택할때 유용 합니다.
    ex) $("img[src='https://tistory1.daumcdn.net']")
 
 
3. 이미지 주소 뒤 에서부터 매칭.
    - 이미지 파일명을 사용하여 선택할때 유용 합니다.
    ex) $("img[src$='epantheo.jpg']")
cs

▼ 제가 작성한 예제 파일도 한번 확인해보세요.
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
<!doctype html>
<html lang="en">
<head>
    <script src="http://code.jquery.com/jquery.min.js"></script>
    <script>
    function src_selector1(){
      $("img[src='https://tistory1.daumcdn.net/tistory/2778128/skin/images/epantheo.jpg']").css("width","200");
    }
    function src_selector2(){
      $("img[src^='https://tistory1.daumcdn.net']").css("width","300");
    }
    function src_selector3(){
      $("img[src$='epantheo.jpg']").css("width","400");
    }
    </script>
</head>
<body>
    <img src="https://tistory1.daumcdn.net/tistory/2778128/skin/images/epantheo.jpg" width="100">
    <br>
    <input type="button" onclick="src_selector1();" value="src 전체 이름으로 선택">
    :: https://tistory1.daumcdn.net/tistory/2778128/skin/images/epantheo.jpg
    <br>
    <input type="button" onclick="src_selector2();" value="src 앞에서부터 검색으로 선택">
    :: https://tistory1.daumcdn.net
    <br>
    <input type="button" onclick="src_selector3();" value="src 뒤에서부터 검색으로 선택">
    :: epantheo.jpg
    <br>
</body>
</html>
cs

▼ 웹상에서 확인한 화면 입니다. 


특정 이미지만 선택하여
작업이 필요할때 src로 선택하면 다른 CSS의 속성과 얽히지 않게 코딩이 가능합니다.



마무리


블로그 스킨 수정할때 딱 좋더라고요


댓글