简体   繁体   中英

Javascript / jQuery : Split content in two parts

I'm not sure if this can be accomplished with Javascript and any help or suggestions greatly appreciated.

Here is a scenario: Let's say I have content (all text), that's 6 paragraphs long. The content is dynamically pulled from the database at once (meaning all 6 paragraphs are outputted through a single variable, so no way for me to change that).

What I need to do is, show the first two paragraphs at the top of the page, then show some other content, then show the remaining paragraphs below the other content.

So, content = 6 Paragraphs

Paragraph One
Paragraph Two

SOME OTHER COOL STUFF IN BETWEEN

Paragraph Three
Paragraph ...
Paragraph Six

Is it possible to split this content with Javascript. The paragraphs are outputted inside p tags.

If it's one long string, unless there's a delimeter I don't see a way of separating. If they are in paragraphs tags already, you can use something like jQuery and .append after the second paragraph tag the content you want using :eq(1) selector.

If each paragraph is wrapped in ap tag then you could do something like this (example is significantly with jquery but wouldn't be too bad with just javascript)

content:

<div id="wrapper">
    <p></p>
    <p></p>
    <p></p>
    <p></p>
    <p></p>
    <p></p>
</div>

script:

<script>
$('#wrapper:nth-child(2)').append("SOME OTHER COOL STUFF IN BETWEEN");
</script>

as regular javascript

<script>
var p3 = document.getElementById('#wrapper').childNodes[2];
var text = document.createElement("p");
text.innerHTML = "SOME OTHER COOL STUFF IN BETWEEN";
p3.insertBefore(text,p3);
</script>

HTML

<div id="wrapper">
    <p>Paragraph 1</p>
    <p>Paragraph 2</p>
    <p>Paragraph 3</p>
    <p>Paragraph 4</p>
    <p>Paragraph 5</p>
    <p>Paragraph 6</p>
    <div id="cool">SOME OTHER COOL STUFF IN BETWEEN</div>
</div>

jQuery

$('#wrapper > p').slice(2).appendTo('#wrapper');

CSS

#cool { font-size:20px; color:red; }

Live demo: http://jsfiddle.net/KZm5X/

You didn't say you were using a library, so here is how to achieve it without a library.

var p = document.getElementById('my-container').getElementsByTagName('p'),
    newDiv = document.createElement('div');

p.parentNode.insertBefore(newDiv, p[2]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM