following is the HTML
<div id="serverList" class="content">
<div class="boxtitle">
</div>
<div id='serverInfo1' class="formEl_b">
<fieldset>
<legend>Server #1</legend>
<div class="section">
<label>
Server Description<small>Linux</small></label>
<div>
<input type="text" id="serverDescription" class="serverDescription medium" /><span class="f_help"></span></div>
</div>
<div class="section">
<label>
Server HostName<small>SRV_FR_TERT</small></label>
<div>
<input type="text" id="serverHostName" class="serverHostName medium" /><span class="f_help"></span></div>
</div>
</fieldset>
</div>
<div id='serverInfo2' class="formEl_b">
<fieldset>
<legend>Server #2</legend>
<div class="section">
<label>
Server Description<small>Windows 2003</small></label>
<div>
<input type="text" id="serverDescription" class="serverDescription medium" /><span class="f_help"></span></div>
</div>
<div class="section">
<label>
Server HostName<small>SRV_EQ_SFGT</small></label>
<div>
<input type="text" id="serverHostName" class="serverHostName medium" /><span class="f_help"></span></div>
</div>
</fieldset>
</div>
<div id='serverInfo3' class="formEl_b">
<fieldset>
<legend>Server #3</legend>
<div class="section">
<label>
Server Description<small>iOS</small></label>
<div>
<input type="text" id="serverDescription" class="serverDescription medium" /><span class="f_help"></span></div>
</div>
<div class="section">
<label>
Server HostName<small>SRV_WR_RQRT</small></label>
<div>
<input type="text" id="serverHostName" class="serverHostName medium" /><span class="f_help"></span></div>
</div>
</fieldset>
</div>
</div>
I am trying to iterate the above html using JQuery and to print description and hostname for every server
$("#serverList").children(".formEl_b").each(function () {
// this is what i am trying to get with no success:
var description = $(".formEl_b .serverDescription").val();
var hostname = $(".formEl_b .serverHostName").val();
alert(description);
alert(hostname);
});
The problem that i’m having is that it always prints the first description and hostname even that there are 3 items of that kind.
Your selector
Is finding all elements with the class
.serverDescriptionthat appear anywhere in the DOM as a descendant of.formEl_b, but since you are already looping the parent elements you can use something like this :Replaces your selectors with
find()to just search the descendants of the current element within theeachloopfind()is marginally faster than using a selector with context (ie$(".serverDescription", this))