Javascript / jQuery: splitting content into two parts

I am not sure if this can be achieved using Javascript, and any help or suggestions that were highly appreciated.

Here is the scenario: let's say I have content (all text) that lasts 6 paragraphs. The content is dynamically pulled out of the database immediately (this means that all 6 paragraphs are displayed through a single variable, so I could not change it).

I need to do this, show the first two paragraphs at the top of the page, then show the other content, and then show the rest of the paragraphs below the other content.

So content = 6 Points

Paragraph One
Paragraph Two

SOME OTHER COOL STUFF IN BETWEEN

Paragraph Three
Paragraph ...
Paragraph Six

Is it possible to break this content into Javascript. Items are displayed inside p-tags.

+3
source share
4 answers

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; }

: http://jsfiddle.net/KZm5X/

+2

, , . , - jQuery .append , :eq(1).

+2

If each paragraph is wrapped in a p tag, you can do something like this (the example is significant with jquery, but won'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>

like 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>
+2
source

You did not say that you are using a library, here's how to do it without a library.

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

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

Source: https://habr.com/ru/post/1784446/


All Articles