IntricatePixels
IntricatePixels

Reputation: 1229

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.

Upvotes: 3

Views: 3318

Answers (4)

Šime Vidas
Šime Vidas

Reputation: 185923

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/

Upvotes: 2

alex
alex

Reputation: 490263

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]);

Upvotes: 0

joekarl
joekarl

Reputation: 2118

If each paragraph is wrapped in a p 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>

Upvotes: 2

Brad Christie
Brad Christie

Reputation: 101614

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.

Upvotes: 2

Related Questions