
1. 동일한 도메인 아이프레임일 경우
$(document).ready(function () {
var iframe = $("#myIframe")[0]; // 아이프레임 요소 가져오기
var iframeDoc = iframe.contentWindow.document; // 아이프레임의 document 객체 가져오기
// 특정 클래스 요소에 여러 개의 속성 추가
$(iframeDoc).find(".target-class").attr({
"data-value": "newData",
"title": "Tooltip Text",
"aria-label": "Accessible Label",
"custom-attr": "customValue"
}).addClass("new-class"); // 클래스 추가
});
2. 다른 도메인의 아이프레임인 경우 (PostMessage 방식)
CORS 문제를 피하기 위해 postMessage를 사용해야 합니다.
부모 페이지 (iframe으로 메시지 보내기)
$("#myIframe")[0].contentWindow.postMessage({
action: "modifyElement",
attributes: {
"data-value": "newData",
"title": "Tooltip Text",
"aria-label": "Accessible Label",
"custom-attr": "customValue"
},
className: "new-class"
}, "*");
아이프레임 페이지 (메시지 수신 및 처리)
window.addEventListener("message", function (event) {
if (event.data.action === "modifyElement") {
$(".target-class")
.attr(event.data.attributes) // 여러 속성 추가
.addClass(event.data.className); // 클래스 추가
}
});
이제 여러 개의 속성을 한 번에 추가할 수 있습니다.
적용할 속성이 많을 경우, 객체를 활용하는 방식이 더 효율적입니다.
#jquery #attr #iframe
반응형
'프로그램' 카테고리의 다른 글
jquery div로 구성하되 조건에 따라 초기 필드를 설정하고, 추가 및 삭제 기능을 구현 (0) | 2025.03.27 |
---|---|
iframe이나 동적으로 생성한 div 내부에서 마우스 좌표값을 얻는 방법 (0) | 2025.03.25 |
JavaScript에서 랜덤 난수를 생성하는 방법 (0) | 2025.03.21 |
JavaScript에서 특정 배열 값을 찾아 새로운 값으로 변경 (0) | 2025.03.19 |
JavaScript에서 특정 배열 값을 찾아 삭제하는 방법 (0) | 2025.03.17 |
댓글