Dev
Dev

Reputation: 31

How to change the background color of the parent?

I'm trying to change the background color of a parent element, using onload.

Codepen: https://codepen.io/gredesign/pen/GmXmPX?editors=1100

<div id="parent">
  <span onload="this.parentNode.style.backgroundColor='grey';">Test</span>
</div>

Upvotes: 2

Views: 3741

Answers (3)

Dev
Dev

Reputation: 31

Here is the answer I was looking for below. Thanks for everyone's help and insight.

https://codepen.io/gredesign/pen/JNarGX?editors=1111

<div id="parent">
<span value="red">123456</span>
</div>
<script> 
  var color = document.getElementsByTagName("span")[0].attributes[0].value; 
  document.getElementById("parent").style.backgroundColor=color;
</script>

Upvotes: 1

Kinna T
Kinna T

Reputation: 804

I think the main issue here might be adding onload instead of breaking it into a js/jquery function. Unless you have a specific need to write it inline, you can simply add an ID or class and reference it in a separate function. This has the added benefit of being able to debug it much more easily.

parentNode is just fine and I see no need to load jquery for a single function that javascript already has under a different name.

Upvotes: 1

hello you can do it with jquery you listenon the loader id and set the background when the loader reach state ready on dom

    $( "#loader").ready(function() {
      $(this).parent().css({backgroundColor: 'red'});
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="parent">
      <span id="loader" >Test</span>
</div>

Upvotes: 1

Related Questions