I am trying to remove an attribute from an element using jQuery.
HTML code
–
<div class="accordion">
<label>Test 1</label>
<article style="max-height: inherit">Content 1</article>
<label>Test 2</label>
<article>Content 2</article>
</div>
jQuery code
–
$(".accordion label").on("click", function(e){
if($(this).next().attr('max-height')){
$(this.next()).removeAttr("max-height");
}
});
It doesn’t trigger the if
part. I think I am missing something simple.
Any help is highly appreciated.
2
Answers
max-height
isn’t an attribute, it’s a style property inside thestyle
attribute. To remove the style property, you’d either use the DOM standardstyle
property, or jQuery’scss
function. (Separately, you also have a typo on the statement inside theif
.) I’d use thestyle
property because you’re looking just for the inline value, not the computed value.Here’s a live example (I’ve changed
max-height: inherit
tomax-height: 2em
so it’s easier to see when it’s removed):When we use
inherit
, we should have that attribute set at upper level. Further the JavaScript written may be as under (which is expressive):and
CSS
for label may be set todisplay:block