Subho Subho - 2 years ago 112
HTML Question

how to get value of inner html objects of a div

i have 3 span elements inside a div. the whole div will be created dynamically inside a loop.
here is the code

$.each(data.Payload, function(index, value){
stmt+='<li class="list-group-item">'+
'<div class="col-xs-12 col-sm-9">'+
'<div class="refugeeInfo">'+
'<span class="name" style="cursor: pointer">'+ value.firstName +' '+value.lastName+'</span><br/>'+
'<label><strong>unID: </strong><span class="unid" style="cursor: pointer;"> '+ value.unID +'</span></label>'+
'<label><strong>rmsID: </strong><span class="rmsid" style="cursor: pointer">'+ value.rmsID +'</span></label><br/>'+

now when i click on (".refugeeInfo") div i need to show the value of name, unID and rmsID. wjat I tried

var name=$(this).children('.name').text();
var unID=$(this).children('.unid').text();
var rmsID=$(this).children('.rmsid').text();
console.log("name: "+name);
console.log("unID: "+unID);
console.log("rmsID: "+rmsID);

but the result showing only name. unID and rmsID is vacant.

Answer Source

Use find() instead of children() Problem is your .unid and .rmsid are nested inside a label tag.. the selector children() works only for direct descendants of the parent. Here these 2 elements are not direct descendants.

From the document.

The .children() method differs from .find() in that .children() only travels a single level down the DOM tree while .find() can traverse down multiple levels to select descendant elements (grandchildren, etc.) as well.

   var name = $(this).children('.name').text();
   var unID = $(this).find('.unid').text();
   var rmsID = $(this).find('.rmsid').text();

   console.log("name: " + name);
   console.log("unID: " + unID);
   console.log("rmsID: " + rmsID);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download