using js/jquery to extract html into two strings (split on a br tag) within occurrences of a wrapping div

StackOverflow https://stackoverflow.com/questions/19039992

Question

I have the following simple html blocks repeated throughout some pages in my site:

<div class="aClass">
<p>first part<br />the remainder of the content</p>
<p>another paragraph><img src="anImage.jpg"/></p>
</div>

What I want to do is capture and create two strings whenever a div with aClass is found in my code. I want the two strings on each occurrence to contain...

1) everything from AFTER the first paragraph opening tag up to the first break 2) everything AFTER the first break and before the FINAL paragraph tag. This could include a wide range of html, multiple paragraphs, bullet lists etc.

Does anyone have any reliable and robust code that could do this?

Was it helpful?

Solution

paragraph = []; 

Initializes array to store content of paragraphs

$('.aClass p').each(function(){ 

Uses jQuery to select paragraph elements that are a descendant of elements with a class of "aClass"

paragraphs.push( $(this).html().split('<br />') );

Takes each paragraph that was selected in the last line and splits it on the <br /> html tag and pushes that into a new position the end of the paragraphs array

});

Ends the jQuery.each function

paragraphs = [];
$('.aClass p').each(function(){
    paragraphs.push( $(this).html().split('<br />') );
});

OTHER TIPS

$(".aClass p").each(function(){
  var strings = $(this).html().split(/<br\s*\/?>/);
  // if there is more than two parts this will cover it
  strings = [strings.shift(), strings.pop()];
  // could also do this if you wanted a trimmed array result
  // strings = strings.splice(1, strings.length-2||0)
  // remember that split on a valid string (including empty) will return at least one entry 
  console.dir(strings);
})

http://jsfiddle.net/24b2b/

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