18

Is it possible to remove the attribute of the first HTML <div> tag? So, this:

<div style="display: none; ">aaa</div>

becomes

<div>aaa</div>

from the following:

<div style="display: none; ">aaa</div>
<a href="#" style="display: none; ">(bbb)</a>
<span style="display: none; ">ccc</span>​
0

6 Answers 6

37

Or pure JavaScript:

document.getElementById('id?').removeAttribute('attribute?')
Sign up to request clarification or add additional context in comments.

1 Comment

jQuery does not always work when jscript is being used at the same time. I get $ undefined errors. Thanks
12

To remvove it from literally the first element use .removeAttr():

$(":first").removeAttr("style");

or in this case .show() will show the element by removing the display property:

$(":first").show();

Though you probably want to narrow it down to inside something else, for example:

$("#container :first").removeAttr("style");

If you want to show the first hidden one, use :hidden as your selector:

$(":hidden:first").show();

2 Comments

Your first example $(":first") doesn't limit itself to the content of the body tag, which I assume is the intention. jsfiddle.net/jqB2b Using $('body :first') works. jsfiddle.net/jqB2b/1
Nick - OK, fair enough. :o) But still worth noting since the first part doesn't do what I assume the OP wanted given the markup in the question.
2

Yes, in fact jQuery has something for this purpose: http://api.jquery.com/removeAttr/

Comments

1

You can use the removeAttr method like this:

$('div[style]').removeAttr('style');

Since you have not specified any id or class for the div, the above code finds a div having inline style in it and then it removes that style from it.

If you know there is some parent element of the div with an id, you can use this code instead:

$('#parent_id div[style]').removeAttr('style');

Where parent_id is supposed to be the id of parent element containing the div under question.

3 Comments

It will remove the style from all divs, while the OP ask specifically for the first one ..
@Gaby: I have also pointed out if there is parent element. For the first div :first filter selector will be needed as already pointed out :)
@Nick Craver: I meant in your answer, sorry should have clarified that :)
0

You say "remove the attribute" — do you mean to remove all attributes? Or remove the style attribute specifically?

Let's start with the latter:

$('div').removeAttr('style');

The removeAttr function simply removes the attribute entirely.

Comments

0

it is easy in jQuery just use

$("div:first").removeAttr("style");

in javascript

use var divs = document.getElementsByTagName("div");

divs[0].removeAttribute("style");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.