Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - Remove the background element - no jQuery

Tags:

javascript

dom

So I have this DOM code :

<div id="foobar">
    H<br />
    e<br />
    l<br />
    l<br />
    o
</div>
<script>
    var foobarElement = document.getElementById('foobar');
    foobarElement.style.backgroundImage = '';
    foobarElement.style.background = '';
    foobarElement.style.backgroundUrl = '';
    foobarElement.style.backgroundColor = 'green';
</script>

With a CSS property on the div :

#foobar {
    background: rgba(0, 0, 0, 0) url("https://www.google.fr/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png") repeat scroll 0 0;
}

(ugly) Fiddle

As you can see, I'm trying to REMOVE entirely the background attribute CSS (in my example the Google Logo), without Jquery.

In my example, I can't edit CSS, neither write DOM stuff before the <div id="foobar">.

NB: all is working fine if in CSS I use background-image with the same url instead of background

Any idea ?

Source:

  • Remove Style on Element
  • https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Properties_Reference
like image 777
4wk_ Avatar asked Nov 13 '15 10:11

4wk_


2 Answers

You should only use the following code:

 var foobarElement = document.getElementById('foobar');
 foobarElement.style.background = 'none';

Setting a style property to '' removes the currently set value and does not set it to an empty one.

The code you have written:

var foobarElement = document.getElementById('foobar');
foobarElement.style.backgroundImage = '';
foobarElement.style.background = '';
foobarElement.style.backgroundUrl = '';
foobarElement.style.backgroundColor = 'green';

Will result into:

<div id="foobar" style="background-color: green">

So the background-image of your #foobar rule is still applied.

If you do just the foobarElement.style.background = 'none'; then it will result into:

<div id="foobar" style="background: none">

Which will overwrite the background-image set by the #foobar rule. Alternatively if you only want to remove the background image then you would use foobarElement.style.backgroundImage = 'none';

like image 51
t.niese Avatar answered Nov 17 '22 21:11

t.niese


Little tricky, anyway working fine , Use

 foobarElement.style.background="0";

https://jsfiddle.net/zn2g73rz/9/

like image 37
Yuvifan Avatar answered Nov 17 '22 22:11

Yuvifan