Conversaciones » Desarrolladores

Why is the CSS assigned through the `style` property not applied?

§
Publicado: 15/02/2019

Why is the CSS assigned through the style property not applied?

People here have gently been suggesting to me that it's time to move away from document.body.innerHTML.replace() and to learn new techniques, because replacing the page html breaks modern pages. Thanks in particular to @wOxxOm for his coaching, it has motivated me to learn more.

I've taken this advice to heart and have been working on converting a script that had brutal html replacement to one that uses gentle DOM manipulation. I'm able to insert elements (yeah!), but I've hit a wall as to how to apply CSS to these elements.

What am I missing?

This part works:

var insertion_point = 'pos-filters' // <div id="pos-filters">
var insert_node = document.getElementById(insertion_point)
if (insert_node) {    
    var new_node = document.createElement('span')
    new_node.innerHTML = to_insert
    // Styling should go here

    // insert as first child
    insert_node.insertBefore(new_node, insert_node.firstChild)
}

However, in the // Styling should go here part, nothing I have tried to insert has any effect. Here are things I've tried:

new_node.style.fontSize = '0.8em !important'
new_node.style.color = 'red' // '#aaaaaa'
new_node.style.textAlign = 'left !important'
new_node.style.setProperty("color", "red")

Whenever I use one of these lines, the text is styled just as it was before.
What's more, the IDE gives me this warning message: Value assigned to primitive will be lost.

Could one of you please tell me what I'm doing wrong?

Big thanks.

§
Publicado: 15/02/2019
Editado: 15/02/2019

@Rex said: What's more, the IDE gives me this warning message: Value assigned to primitive will be lost.

Could one of you please tell me what I'm doing wrong?

You are not including semicolons at the end of your lines. This is probably why you are getting the value assigned error. You can check for mistakes like this using something like https://jshint.com/

§
Publicado: 15/02/2019

Thank you for your kind help troubleshooting, @adisib!

Added semi-colons. The IDE still gives the warning, and on the GreaseMonkey side the CSS still has no effects on the page.

CSS problem in IDE

§
Publicado: 15/02/2019

Inspecting the page, I see that the generated html is:

<span style="">

What to do for the style to stick?

§
Publicado: 15/02/2019

This worked:

new_node.style.setProperty('font-size', '0.8em', 'important')
new_node.style.setProperty('text-align', 'left', 'important')
§
Publicado: 06/04/2019

Besides the missing semicolons, the problem with the simpler cssPropertyName syntax is the !important keyword (which in most cases you don't need). See https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleDeclaration/setProperty

Publicar respuesta

Inicia sesión para responder.