특정 iframe을 선택할 때, src 속성의 특정 부분을 기준으로 선택하고자 할 때 URL의 고유한 식별자 부분을 제외한 방식으로 적용하려면, 속성 선택자를 활용할 수 있습니다. src URL에 포함된 다른 고유한 부분을 사용하거나, 더 일반적으로 title 속성을 기준으로 선택할 수 있어요.
방법 1: src 속성에서 특정 부분만 이용해 선택하기
URL의 src 속성 값이 고유한 패턴을 포함하고 있다면, src 속성을 사용해서 해당 iframe을 선택할 수 있습니다. 예를 들어, youtube.com/embed/ 이 부분은 여러 iframe에서 공통으로 나타날 수 있기 때문에, 이 부분만 기준으로 선택할 수 있어요.
CSS로 src의 일부분으로 선택
iframe[src*="youtube.com/embed/"] {
position: sticky;
top: 60px;
z-index: 9999;
}
iframe[src*="youtube.com/embed/"]는src속성 값에"youtube.com/embed/"를 포함하는 모든iframe을 선택합니다.- 이 방법은 모든
YouTube비디오를 포함한iframe에 스타일을 적용합니다.
JavaScript로 src의 일부분으로 선택
const iframe = document.querySelector('iframe[src*="youtube.com/embed/"]');
iframe.style.position = 'sticky';
iframe.style.top = '60px';
iframe.style.zIndex = '9999';
document.querySelector('iframe[src*="youtube.com/embed/"]')는src속성에"youtube.com/embed/"를 포함하는 첫 번째iframe을 선택하고, 스타일을 적용합니다.
방법 2: title 속성 사용하기
iframe의 title 속성도 고유할 수 있기 때문에, title 속성에 따라 선택할 수 있습니다.
CSS로 title 속성으로 선택
iframe[title="YouTube video player"] {
position: sticky;
top: 60px;
z-index: 9999;
}
iframe[title="YouTube video player"]는title속성 값이"YouTube video player"인iframe을 선택합니다.
JavaScript로 title 속성으로 선택
const iframe = document.querySelector('iframe[title="YouTube video player"]');
iframe.style.position = 'sticky';
iframe.style.top = '60px';
iframe.style.zIndex = '9999';
document.querySelector('iframe[title="YouTube video player"]')는title속성 값이"YouTube video player"인 첫 번째iframe을 선택합니다.
방법 3: nth-of-type 선택자 사용하기
iframe이 특정 순서대로 배치되어 있다면, nth-of-type 선택자를 사용해서 위치에 따라 선택할 수 있습니다.
CSS로 nth-of-type 사용
iframe:nth-of-type(1) {
position: sticky;
top: 60px;
z-index: 9999;
}
iframe:nth-of-type(1)은 페이지 내 첫 번째iframe을 선택합니다.- 숫자를 바꾸면 다른 순서의
iframe을 선택할 수 있습니다.
JavaScript로 nth-of-type 사용
const iframe = document.querySelectorAll('iframe')[0]; // 첫 번째 iframe
iframe.style.position = 'sticky';
iframe.style.top = '60px';
iframe.style.zIndex = '9999';
document.querySelectorAll('iframe')[0]는 첫 번째iframe을 선택하고, 그 스타일을 변경합니다.
방법 4: iframe 안에서 동적으로 스타일 적용하기 (JavaScript)
모든 iframe을 선택하고 특정 조건에 맞는 iframe을 찾아 스타일을 적용할 수 있습니다. 예를 들어, iframe이 특정 속성을 가지고 있다면, 이를 기준으로 선택할 수 있습니다.
const iframes = document.querySelectorAll('iframe');
iframes.forEach(iframe => {
if (iframe.src.includes("youtube.com/embed/")) { // 특정 조건
iframe.style.position = 'sticky';
iframe.style.top = '60px';
iframe.style.zIndex = '9999';
}
});
iframe.src.includes("youtube.com/embed/")를 사용해src에"youtube.com/embed/"가 포함된iframe을 찾아 스타일을 적용합니다.- 이 방법은 여러
iframe을 한 번에 처리할 수 있습니다.
요약
특정 iframe을 선택하고 스타일을 적용하는 방법은 다양한 방식이 있습니다
src속성의 일부 값을 기준으로 선택 (예:youtube.com/embed/)title속성으로 선택nth-of-type로 순서를 기준으로 선택- JavaScript로 조건에 맞는
iframe을 동적으로 선택하여 스타일을 적용
이 방법들 중에서 원하는 방식에 맞게 선택하면 됩니다~!
