简体   繁体   中英

Why isn't my css style changing?

I am trying to change the color of the text using javascript but something as simple as this isnt working and I dont understand why..

 <!DOCTYPE html> <html> <script> var y = document.getElementById('ya'); y.style.color = "red"; </script> <p style="font-size:100px;" id="ya"> hi </p> </html> 

Try this, it's working. This is because the script now runs after the DOM element renders.

 <p style="font-size:100px;" id="ya"> hi </p> <script> var y = document.getElementById('ya'); y.style.color = "red"; </script> 

Because the javascript was loaded before your p tag. If you check the console you will see an error "TypeError: Cannot read property 'style' of null.

 <!DOCTYPE html> <html> <p style="font-size:100px;" id="ya"> hi </p> <script> var y = document.getElementById('ya'); y.style.color = "red"; </script> </html> 

The element id you were trying to find wasn't in the DOM as your script runs before the DOM element renders.

Your DOM position should come first then Script to manipulate the DOM element.

There are two solution for this problem :

1. Move your Script below the DOM.

<p style="font-size:100px;" id="ya">
    hi
</p>
<script>
  var y = document.getElementById('ya');
  y.style.color = "red";
</script>

2. use jQuery document.ready()

<p style="font-size:100px;" id="ya">
    hi
</p>
<script>
 $(document).ready(function() {
   var y = document.getElementById('ya');
   y.style.color = "red";
 });
</script>

An Element with id='ya' is undefined at the time you wrote the JavaScript. Put the JavaScript in your head and use onload = function(){/* code here */} or addEventListener('load', function(){/* code here */}) and it should work every time (Well maybe not the first way if you have multiple onloads. But there's a way around that by assigning onload to a var then executing after the other onload). Really I would use External JavaScript, so it's stored in your Clients cache, this will improve site performance. Just make sure you change your file name if you update your JavaScript, if your site is deployed, or just clear your cache if your still working on it.

first you can check jQuery.min.js in included in your file your code is fine.

test this one

   <script>
      var y = document.getElementById('ya');
       y.css("color", "red");
   </script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM