I wanted to get the child element’s id using JQuery using the following technique.However, it seems the code cannot be executed in the loop..Why this is happening and how can I get each child’s id?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>JQuery</title>
<script type="text/javascript" src="jquery.js"> </script>
<style type="text/css">
#parent{width:50%;margin:auto;border:#000 thick groove;overflow:hidden;}
#child1{float:left;width:50px;height:50px;background-color:#00F;}
#child2{float:left;width:50px;height:50px;background-color:red;margin-left:30px}
#child3{float:left;width:50px;height:50px;background-color:#00F;}
#child4{float:left;width:50px;height:50px;background-color:red;margin-left:30px}
#child5{float:left;width:50px;height:50px;background-color:#00F;}
#child6{float:left;width:50px;height:50px;background-color:red;margin-left:30px}
#child7{float:left;width:50px;height:50px;background-color:#00F;}
#child8{float:left;width:50px;height:50px;background-color:red;margin-left:30px}
</style>
</head>
<body>
<div id="parent">
<div id="child1"></div>
<div id="child2"></div>
<div id="child3"></div>
<div id="child4"></div>
<div id="child5"></div>
<div id="child6"></div>
<div id="child7"></div>
<div id="child8"></div>
</div>
<script type="text/javascript">
var child = $('#parent').children().length;
var chil;
for (i = 0;i<child;i++){
chil = $('#parent').children()[i].attr('id');
alert(chil);
}
</script>
</body>
</html>
children()[i]is returning the dom element not a jquery object so you can’t callattron it. If you change it tochildren().eq(i).attrit should work.