user858599
user858599

Reputation: 23

Why doesn't JQuery's removeAttr always work?

When trying to see why removeAttr doesn't always seem to work I tried.

$("div#mydiv").css('height','200px');  
$("table").removeAttr("border");  
$("#mydiv").removeAttr("height");  

The table borders attribute is removed OK but not the div height attribute. I need to use other suggested methods such as

$("#mydiv").css('height','auto')  

to alter it but not actually remove it.

I would be interested to know what makes removeAttr not work in this scenario? There is no other css anywhere.

Upvotes: 1

Views: 4559

Answers (4)

cwallenpoole
cwallenpoole

Reputation: 82028

removeAttr refers to the attributes of the tag. So, given:

<span title="my-title" id="my-id" style="height: 4px; padding: 200px;" />

That span has three attributes, title, id, and style. removeAttr will let you remove any of these. But here's the trick, while removeAttr will let you remove the style attribute, it can only remove both height and padding, it cannot edit either.

This:

$("#my-id").removeAttr("style");

results in:

<!-- not literally, but this is the best way to explain it -->
<span title="my-title" id="my-id" />

css, on the other hand, lets you edit that style attribute directly.

This:

$("#my-id").css("height", "2px");

results in:

<span title="my-title" id="my-id" style="height: 2px; padding: 200px;" />

Now, to remove just the height, you can pass an empty string to the second parameter.

This:

$("#my-id").css("height", "");

results in:

<span title="my-title" id="my-id" style="padding: 200px;" />

Upvotes: 7

Joe
Joe

Reputation: 82614

Use jQuery's height:

$(document).ready(function() {
    $("div#mydiv").css('height', '200px');

    $('#clicker').click(function() {
        $('#mydiv').height('')
    });
});

Example jsFiddle

Upvotes: 1

BZink
BZink

Reputation: 7957

This is supposed to work on attributes like id, href, disabled, selected, etc... Even css that's used inline is part of the "style" attribute. You could remove the style attribute but not pieces inside of it.

You may try $("#mydiv").css('height', '');

I don't recall what happens when you pass an empty string the the css function.

Upvotes: 1

Fad
Fad

Reputation: 9858

The height is an inline css styling which means it's inside the style attribute. I think you can do this instead

$('#mydiv').css('height', '');

Upvotes: 4

Related Questions