How to access a hidden dom element using jQuery?

I have an HTML Div (I use Twitter Bootstrap for hide-show div2 ) that looks like this:

HTML:

 <div id="div1"> <button id="mybtn">Button</button> <div id="div2" class="modal hide fade span12" style="display: none;"> <button id="anotherButton" data-char="">AnotherButton</button> </div> </div> 

With jQuery im trying to change the value of data-char while im is clicking on mybtn . But without success, the reason div2 is hidden. console.log($('#anotherButton')); returns an empty array.

Is there a way to access a hidden DOM with jQuery or Javascript?

* Edit: * Having tried that this does not work better, return undefined :

 $('#mybtn').live('click', function(e) { //or e.preventDefault(); $('#anotherbutton').attr("data-char", "assigned"); alert($('#anotherbutton').attr("data-char")); }); 
+4
source share
4 answers

It seems that the data method will not work with elements that are in a hidden state. You must use the attr method.

This should work fine.

 $(function(){ $("#mybtn").click(function(e){ e.preventDefault(); $("#anotherButton").attr("data-char","new value"); }); }); 

Working sample http://jsfiddle.net/kshyju/a7Cua/4/

+1
source

You can assign it

Live demo

 $(function(){ $('#anotherButton').attr('char', "assigned"); alert($('#anotherButton').attr('char')); });​ 

at the touch of a button

Live demo

 $(function(){ $('#anotherButton').attr('data-char', "assigned"); alert($('#anotherButton').attr('data-char')); });​ 
+3
source

The fact that it is hidden does not change anything. Probably the problem is that the js code is in front of the HTML button. Either put it, or put it in a listener, such as $(document).ready() , to make sure that it was processed when you try to access it.

+1
source

Try $(button:hidden)

This usually works for things like this.

Source: Http://api.jquery.com/hidden-selector/

0
source

All Articles