Reddy
Reddy

Reputation: 1497

Split and display Child ID from Parent ID

I have a div with ID as "parentID" to the parent div and based on this, I am dynamically adding "ChildID" to all its child divs along with its "parentID".

jQuery(document).on('click', '.split-id', function() {
  var parentID = jQuery('.parent').attr('id');
  var childID = jQuery('.child').attr('id', jQuery(this).closest('.parent').attr('id') + 'ChildID');

  jQuery('#displayParentID').html('Parent ID : ' + parentID);
  jQuery('#displayParentChildID').html('Parent Child ID : ' + childID);
  jQuery('#displayOnlyChildID').html('Child ID only : ' + childID);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="parent" id="parentID">
  <div class="child"></div>
  <div class="child"></div>
</div>

<div id="displayParentID"></div>
<div id="displayParentChildID"></div>
<div id="displayOnlyChildID"></div>

<a href="javascript:;" class="split-id">Split</a>

How can I get all child element IDs without parent div IDs? like below onClicking of Split tag...

Parent ID : parentID
Parent Child ID : parentIDChildID
Child ID only : ChildID (This is what I am expecting)

Fiddle

Upvotes: 1

Views: 408

Answers (1)

shemekh
shemekh

Reputation: 456

Don't know what exactly is purpose of what you are asking, but you can replace your js code in your fiddle with this and it works as you expected. * Mind that, when you use attr function to set a property it is returning Object, not only string label. * If you will give multiple children the same id it will not work, because in html code ids need to be unique

jQuery(document).on('click', '.split-id', function () { 

  var parentID = jQuery('.parent').attr('id');
  var childElement = jQuery('.child').attr('id', parentID + 'ChildID');
  var childID = childElement.attr('id');
  jQuery('#displayParentID').html('Parent ID : ' + parentID);
  jQuery('#displayParentChildID').html('Parent Child ID : ' + childID);
  jQuery('#displayOnlyChildID').html('Child ID only : ' + childID.replace(parentID, ''));  

});

If you have some more questions, go on and ask.

Upvotes: 1

Related Questions