How to use Javascript to add multiple style properties to one element?

javascript html css text-styling

6223 просмотра

2 ответа

33 Репутация автора

I've tried various renditions of this code to try and change a certain element for a coding exercise but non of them seems to be able to change multiple styling properties of an element on a button click. Would love some assistance. Thanks!

document.getElementById("Combo Style").onclick = function() { document.getElementById ("More Text").style.fontSize.color = "50px , #BB65C5"; }

Автор: West Coast Charlie Источник Размещён: 18.07.2016 12:41

Ответы (2)


0 плюса

8815 Репутация автора

Решение

To achieve your expected result use setAttribute
HTML:

<button id="Combo Style">Change</button>
<div id="More Text">abcd</div>

JS:

document.getElementById("Combo Style").onclick = function() {
  document.getElementById("More Text").setAttribute("style", "font-size:50px;color:red;");

}

http://codepen.io/nagasai/pen/AXVWwO

Автор: Naga Sai A Размещён: 18.07.2016 12:48

-2 плюса

1073 Репутация автора

You need to grab the element by using id or any selector and use style property or css text property to apply css. Check the below code -

    var element=document.getElementById("More Text");
    element.style.fontSize="20px";
    element.style.color="red";
    element.style.background="blue";

You can also use cssText property, like -

document.getElementById("More Text").style.cssText='fontSize="20px";color="red";'

This will insert an inline style tag in the element with the csstext property.

Автор: Ujjwal Kumar Gupta Размещён: 18.07.2016 06:25
Вопросы из категории :
32x32