I.Am.A.Guy I.Am.A.Guy - 1 year ago 46
Javascript Question

jQuery code that searches for a div and sets an attribute

I was working on a piece of code that looked for a div that had the css style

clear: both
after the page loaded and then added css
display: none
.

This is a sample of my code :

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js" type="text/javascript"></script>
<script>
$(document).load(function () {
if( $("div").css('clear').toLowerCase() == 'both') {
$(this).css("display", "none");
});
});
</script>
<title>Check</title>
</head>
<body>
<div>This is visible</div>
<div style="text-align: center; font-size: smaller; clear: both;">This is not visible.</div>
</body>
</html>


For some reason, this code does not seem to work out...I'm kind of new to jQuery. Can someone point out my error?

Answer Source

You can use css() method like following.

$('div').css('display', function () {
    if ($(this).css('clear') == 'both')
        return 'none'
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>This is visible</div>
<div style="text-align: center; font-size: smaller; clear: both;">This is not visible.</div>

Update: Use $(document).ready instead of $(document).load.