Search code examples
javascripthtmlcssangularionic-framework

Updating the background-color of .pane and .view within an ionic web app with javascript


I am trying to update the background-color of two css selectors named .pane and .view located within the file ionic.css. However, when I attempt this nothing changes. I can go directly to the ionic.css file to change it but I want to change it with javascript directly in the index.html file. I've tried using querySelectorAll(".view") and querySelectorAll(".pane") but when I check the contents of the NodeList, it is empty. The code for index.html is included below:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
    <title></title>

    <link rel="manifest" href="manifest.json">

    <!-- un-comment this code to enable service worker
    <script>
      if ('serviceWorker' in navigator) {
        navigator.serviceWorker.register('service-worker.js')
          .then(() => console.log('service worker installed'))
          .catch(err => console.log('Error', err));
      }

    
    </script>-->

    <link href="lib/ionic/css/ionic.css" rel="stylesheet">
    <link href="css/style.css" rel="stylesheet">

    <!-- IF using Sass (run gulp sass first), then uncomment below and remove the CSS includes above
    <link href="css/ionic.app.css" rel="stylesheet">
    -->

    <!-- ionic/angularjs js -->
    <script src="lib/ionic/js/ionic.bundle.js"></script>
<script src="lib/ionic/js/angular/angular-resource.min.js"></script>
    <!-- cordova script (this will be a 404 during development) -->
    <!--<script src="cordova.js"></script>-->

    <!-- your app's js -->
    <script src="js/app_courses.js"></script>
    
    <script src="js/controllers_2_courses.js"></script>
      
        <script src="js/services_courses.js"></script>
     
  </head>

 <body ng-app="CITC">
    <ion-nav-view></ion-nav-view>

     <script> 

  // Get references to the elements
  const paneElements = document.querySelectorAll('.pane');
  const viewElements = document.querySelectorAll('.view');

  // Update the background color for each element
  paneElements.forEach((element) => {
    element.style.backgroundColor = '#111D12';
  });

  viewElements.forEach((element) => {
    element.style.backgroundColor = '#111D12'; 
  });

    </script> 

    
  </body>
</html>

Solution

  • CSS will always take the last defined style in the order of styles defined, so we can just create a new style tag and insert our CSS programmatically and it will override ionic.css!

    const style = document.createElement('style');
    style.type = 'text/css';
    style.innerHTML = '.pane, .view { background-color: #111D12; }';
    const headTag = document.getElementsByTagName('head')[0];
    headTag.appendChild(style);
    

    This isn't the angular way to handle it, but still it will get you what you want!