0

sorry i'm new in jquery and i need help :-( i want to traverse all elements on html page with class parts then go inside to two children and pass them a random number ( the same for them both)

for every element new random number is passed ( no repeat on page) children classes are : anot-head anot-body this is a sample code:

    $(document).ready(function() {

$.each($('.parts'), function(){
var ran=Math.floor(Math.random()* 1000000);

$( ".anot-head" ).attr( "data-toggle","collapse" ).attr( "href","#s"+ran );
$( ".anot-body" ).attr( "id","s"+ran );

});
}); 

2 Answers 2

2

$(".anot-body") does a search of the whole document, if you want to find a particular element in another element you need to do a search from that parent element.

In your case you would do a search on the particular .parts element that is currently being iterated over in your $.each() callback

$('.parts').each(function(index,element){
  var parent = $(element);
  var ran=Math.floor(Math.random()* 1000000);
  parent.find('.anot-head').attr( "data-toggle","collapse" ).attr( "href","#s"+ran );
  parent.find('.anot-body').attr( "id","s"+ran );
});
Sign up to request clarification or add additional context in comments.

1 Comment

extremely unlikely, but still possible to get duplicates
0

No need to use random.... use index of each

$('.parts').each(function(index){
  var $part = $(this); 
  $part.find('.anot-head').attr({"data-toggle":"collapse","href":"#s"+index});
  $part.find('.anot-body').attr("id","s"+ index);
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.