Question

I have some markup where there are img tags and sometimes a paragraph between the images. I want to use javascript(jQuery) to find this element, if it exists. But, this markup is inserted via CKEditor, so the exact markup may vary.

Ideally, the markup would look like this:

<img src="something.jpg">
<img src="something2.jpg">
<p>Some text</p>
<img src="something3.jpg">
<p>Some other text</p>

But it may be something more like this:

<img src="something.jpg">
<br>
<p>Some text</p>
<img src="something2.jpg">
<p>Some text</p>
<img src="something3.jpg">
<br>
<p>Some text</p>

So I would probably have to create an array of the img tags, loop through each and find the

between this img tag and the next, wherever it might be. How would I do that using jQuery?

It might be something like this:

var img_array = $('#container').find('img');

img_array.each(function(){
   // Do something here
})

Edit: Here's how I ended up doing it:

var img_array = $('#container').find('img');
img_array.each(function(){
  var between = $(this).nextUntil('img');
  var text = between.text();
})

nextUntil returns a set of elements that is between. So I just strip it away and keep the simple text only. Works like a cherrm! :)

Was it helpful?

Solution

You can simply use nextUntil.

For example, the following will match every <p> tags between the matched image and the next one.

$('img[src="something.jpg"]').nextUntil('img', 'p');


<img src="something.jpg">
<br>
<p>Some text</p>            <--
<img src="something2.jpg">

OTHER TIPS

You cant select using basic jquery selector like $( "img + p" ) and $( "img + br + p" ) this will select the element you want to use.

http://jsfiddle.net/WFnWW/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top