最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - using jsjquery to extract html into two strings (split on a br tag) within occurrences of a wrapping div - Stack Ov

programmeradmin1浏览0评论

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 0
Add a ment  | 

2 Answers 2

Reset to default 3
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 />') );
});
$(".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/

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论