2017-03-06 1 views
1

두 개의 버튼 (업데이트, 저장)에 CSS 속성을 설정하는이 부분이 있습니다. 나는 코드 줄을 최소화하기 위해 노력하고있어 모든 CSSElementById 작성하는 대신 여러 HTML 요소에 CSS 속성을 설정하는보다 효율적인 방법을 찾고 있어요. querySelectorAll이이 컨텍스트에서 사용하기에 적합한가?여러 HTML 요소에 CSS 속성 설정

// 크리스

var css = {"backgroundColor": "red","textDecoration": "line-through"}; 
    for (var prop in css) { 
    document.getElementById("update").style[prop] = css[prop]; 
    document.getElementById("save").style[prop] = css[prop]; 
    } 
+0

'.style' 다음에 점이 있어야합니다. –

+0

예, querySelectorAll은이 컨텍스트에서 사용하기에 적합합니다. – Pineda

+0

querySelector 사용할 수 있지만 스타일을 설정하려면 쿼리의 결과를 반복하고 배열의 각 요소에 대한 스타일을 설정해야합니다. – Andrey

답변

1

예, querySelectorAll이 상황에서 사용할 수있는 사용됩니다

var css = {"backgroundColor": "red","textDecoration": "line-through"}; 
var elements = document.querySelectorAll('#update, #save'); 
for (var prop in css) { 
    elements.forEach(function (element) { 
     element.style[prop] = css[prop]; 
    }); 
} 

에게 건의 할 것입니다. IE8 이전 버전에서는 지원되지 않습니다. Check out the MSN docs for some quirks.

또한, querySelectorAll 객체와 같은 배열 (비 라이브 NodeList를)을 반환한다는 것을 알고 그래서 당신은 이러한 구조와 작동하도록 코드를 수정해야합니다 :

var css = {"backgroundColor": "red","textDecoration": "line-through"}; 

var matched = document.querySelectorAll("#update, #save"); 
matched.forEach(function (c){ 
    c.style.backgroundColor css.backgroundColor; 
    c.style.textDecoration = css.textDecoration; 
}); 
+0

유익한 답변을 주셔서 감사 드리며 또한 호환성 문제를 알려 주셔서 감사합니다. 다행히도 IE10 이상의 사용자 만이 영향을받습니다. 비슷한 것을 시도해 보겠습니다. – koffe14

+0

당신이 내 대답을 찾았 기 때문에 기쁘다 :-) – Pineda

1

나는 다음과 같은 방법을 여기에 querySelectorAll 여러 선택기

0

document.querySelectorAll을 사용하여 이런 식으로 할 수 있습니다.

/*declare a css class*/ 

.button-css{"backgroundColor": "red","textDecoration": "line-through"}; 

/*in javascript you can do the following*/ 
var buttons=document.querySelectorAll(".buttons"); 

buttons.forEach(function(button){ 
    button.classList.add('button-css'); 
})