简体   繁体   中英

Changing CSS with DOM getElementsByName

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>

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

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

But if you only have one, why not just use the id ? <div> s shouldn't really have name s 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.

Try this

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

and remove !important from css class for visibility attribute

JS Fiddle Example

You've set everything as !important . That takes precedence over inline styles. The quickest solution would be to set style.visibility = 'visible!important' , or you could unimportant the importants.

Thanks to you all for your suggestions, the biggest problem was the !important over-riding most of the JS. I switched to using display and removed the !important. Code as follows. I ended using another function to hide the divs and a case to show them as the random generator made the input as to which case was visible.

document.getElementById("circle1").style.display = "block";

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