clase innerHTML

I am working with a javascript function which takes a value from a <input type="text" /> and then write it as a text without being an input. I do this using innerHTML y funciona perfectamente.

My question is: How can I use a CSS class to edit the color and size of the text I am writting with innerHTML

var element = document.getElementById("element");
var value = document.getElementById("value").value;
element.innerHTML = value;

¡Gracias!

preguntado el 31 de enero de 12 a las 16:01

Id suggest using element.textContent = value; instead. Modifying the innerHTML is icky. -

3 Respuestas

JavaScript:

element.className = 'foo';
// or
element.className += ' foo';

CSS:

.foo {
    color: #F00;
    font-size: 2em;
}

Or, more advanced: elem.classList.add( 'foo' ); (As usual, IE gets the polyfill via conditional comments.)
– Šime Vidas

Respondido el 31 de enero de 12 a las 21:01

Or, more advanced: elem.classList.add( 'foo' ); (As usual, IE gets the polyfill via conditional comments.) - Šime Vidas

If your element's ID is "element" just add the following css:

#element{
    color: #000000;
    font-size: 24px;
    font-family: sans-serif;
}

And mess with the values until it suits you.

Respondido el 31 de enero de 12 a las 20:01

With JS you can manipulate the css directly without the need of an extra class (besides, you already have an ID, you could use styles on...): Once you have selected your element

var el = document.getElementById("element");

Puedes llamar

el.style.<css-style> = ...;

with css-style being a css-declaration. Note that they are not hyphenated but notated with CamelCase -> backgroundColor en lugar de background-color.

Firebug can give you content assist on that

Respondido el 31 de enero de 12 a las 21:01

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.