Changing CSS with DOM getElementsByName

12,305

Solution 1

Try this

function showCircle(){
    document.getElementsByName("circle")[0].style.visibility="visible";  
}

and remove !important from css class for visibility attribute

JS Fiddle Example

Solution 2

getElementsByName returns a NodeList of elements. If you want the first element, say so:

document.getElementsByName("circle")[0].style.visibility = "visible";

But if you only have one, why not just use the id? <div>s shouldn't really have names anyways...

document.getElementById('circle').style.visibility = 'visible';

If there are many, you might consider using classes instead. (And classes for the visibility might be better, too!)

Finally, stop making all your styles !important for no good reason. There is almost never a good reason to make any rules important, and it can make everything a mess of !important when specificity would have made things much nicer. If you just threw those in to try and fix something... that made it worse.

Share:
12,305
Mark H
Author by

Mark H

Learning to code: JS, C, Ruby, objC, HTML5, and CSS3.

Updated on June 05, 2022

Comments

  • Mark H
    Mark H almost 2 years

    I am trying to make changed to CSS with the DOM in JS, I have succeeded with changing the HTML attributes but not the CSS attributes. It seems that CSS is not affected by this particular DOM.

    Code looks like this...

    <style>
        #circle1{
    
                width: 50px !important;
                height: 50px !important;
                position: absolute !important;
                top: 200px !important;
                left: 405px !important;
                background: black !important;
                border-bottom-left-radius: 50px !important;
                border-bottom-right-radius: 50px !important;
                border-top-left-radius: 50px !important;
                border-top-right-radius: 50px !important;
                z-index: 10 !important;
                visibility: hidden !important;
    
        }
    
    
        </style>
    </head>
    
    <body>
    <script type="text/javascript">
    function showCircle(){
        document.getElementsByName ("circle").style.visibility="visible";  
    }
    
    </script>
    <div id="circle1" name="circle"></div>
    
    <input type="button" onclick="showCircle()" value="show circle with display property">
    </body>
    
  • Mark H
    Mark H about 11 years
    Yes I learned after posting that the !important was an area of problem.
  • Mark H
    Mark H about 11 years
    Your absolutely right the !important was my biggest issue. I removed it from the code and was able to then move to the next stage of testing for the problem.
  • Mark H
    Mark H about 11 years
    Yup it was the crux of the problem.