<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.3/jquery.min.js"></script>
<script type="text/javascript">
$( document ).ready( function(){
$( "table > tr > td > input[id]" ).each( function( i, element ){
alert( $( element ).attr( 'id' ) )
});
});
</script>
</head>
<body>
<form>
<table>
<tr><td>City:</td><td><input type="text" id="city" name="city" /></td></tr>
<tr><td>state:</td><td><input type="text" id="state" name="state" /></td></tr>
</table><br />
<input type="submit" value="OK"/>
</form>
</body>
</html>
When I write it this way, it doesn’t work because my browser automatically creates a <tbody>
tag. So I have to write:
$( "table tr > td > input[id]" ).each( function( i, element ){
alert( $( element ).attr( 'id' ) )
});
or:
$( "table > tbody > tr > td > input[id]" ).each( function( i, element ){
alert( $( element ).attr( 'id' ) )
});
Can I rely on the implicit creation of the <tbody>
tag, or should I not count on that?
Edit: added to explain my comment to Tim Down’s answer:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.3/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.js"></script>
<script type="text/javascript">
$( document ).ready( function() {
var ids = [];
var form = document.forms[0];
var formEls = form.elements;
var f_len = formEls.length;
for ( var i = 0; i < f_len; ++i ) {
ids.push( formEls[i].id );
}
var data = [ [ 'one', 'two', 'thre' ], [ 'four', 'five', 'six' ] ];
var ids_len = ids.length;
for ( i = 0; i < ids_len; i++ ){
$( "#" + ids[i] ).autocomplete({
source: data[i]
});
}
});
</script>
</head>
<body>
<form>
<table>
<tr><td>A:</td><td><input type="text" id="a" name="a" /></td></tr>
<tr><td>B:</td><td><input type="text" id="b" name="b" /></td></tr>
</table><br />
<input type="submit" value="OK"/>
</form>
</body>
</html>
When I run this, the web console shows me a warning like this: Empty string to getElementById() is passed
. One of the strings returned by form.elements
is empty.