views:

211

answers:

2

I have one form on a page which has a bunch of sibling tags. I'd like to retrieve the text between each h5 tag using jQuery. I'd preferably like to have a callback or be able to do this in a simple looping construct where I can grab the text and make meaningful HTML of it, then insert the final string somewhere else.

How does one do this with jQuery?

+6  A: 

This will grab all h5 under the form and alert their text. You can do whatever from there.

$('#myform h5').each(function() {
    alert($(this).text());
});
Paolo Bergantino
A: 

By sibling tags you mean they are at the same level than the form, like this?:

<form id="the-form">
  ...
</form>
<h5>Title 1</h5>
<h5>Title 2</h5>
<h5>Title 3</h5>

If that's correct, you can do something like:

$("#the-form ~ h5").each(function (){
  // do something with $(this).text()
});

Note the ~, which selects siblings.

Or, if you prefer to send the text to a callback:

function callback( textFound ){
  // do something with textFound
}

$("#the-form ~ h5").each(function (){
  callback( $(this).text() );
});
Seb