www.webdeveloper.com
Results 1 to 5 of 5

Thread: Simple, ..yet doesn't work

  1. #1
    Join Date
    Mar 2010
    Posts
    281

    Simple, ..yet doesn't work

    just wondering why my syntax isn't working here..

    this doesn't work...
    PHP Code:
    function setBg() {
    el document.getElementsByTagName('body');
    el.style.backgroundColor "#f9f363";

    but this does.....


    PHP Code:
    function setBg() {
    document.body.style.backgroundColor "#f9f363";


  2. #2
    Join Date
    Dec 2011
    Location
    Centurion, South Africa
    Posts
    792
    getElementsByTagName returns a collection, so this should work:

    Code:
    function setBg() { 
    el = document.getElementsByTagName('body')[0]; 
    el.style.backgroundColor = "#f9f363"; 
    }
    JavaScript: Learn | Validate | Compact

  3. #3
    Join Date
    Dec 2005
    Location
    FL
    Posts
    7,350

    Lightbulb

    Quote Originally Posted by toptomato View Post
    just wondering why my syntax isn't working here..

    this doesn't work...
    PHP Code:
    function setBg() {
    el document.getElementsByTagName('body');
    el.style.backgroundColor "#f9f363";

    but this does.....


    PHP Code:
    function setBg() {
    document.body.style.backgroundColor "#f9f363";

    getElementsByTagName() returns an array, not an individual value.
    Needs to be accessed like an array element.
    See:
    Code:
    <script type="text/javascript">
    function setBG() {
      el = document.getElementsByTagName('body');
      el[0].style.backgroundColor = "#00f363";
    } 
    
    function SETbg() {
      document.body.style.backgroundColor = "#f9f363";
    } 
    </script>
    <body>
    <button onclick="setBG()">Tag BG set</button>
    <button onclick="SETbg()">DOM BG set</button>
    </body>

  4. #4
    Join Date
    Mar 2010
    Posts
    281
    ahh yes, got it. thank you!

  5. #5
    Join Date
    Dec 2005
    Location
    FL
    Posts
    7,350
    You're most welcome.
    Happy to help
    Good Luck!

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles