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?
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?
Share Improve this question edited Sep 26, 2013 at 23:03 AdamJones asked Sep 26, 2013 at 22:50 AdamJonesAdamJones 6011 gold badge15 silver badges42 bronze badges 02 Answers
Reset to default 3paragraph = [];
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 />') );
});
$(".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/24b2b/