Javascript / jQuery : Split content in two parts - javascript

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.

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/

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

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

Related

Append a div with dynamic text to another div without losing the data - javascript

I have a question that might seems easy but I can't seem to find a solution.
<div class="text">
<p class="paragraph">
<span>The main text is this one </span>
<span class="bold">with bold text near</span>
</p>
<p class="bold-dynamic" style="" data-message-code="dynamic-message">Add me near the other paragraph without losing the dynamic content</p>
</div>
So basically, I have to unite all these paragraphs + spans together on one line without losing the dynamic content I am getting in the 3rd paragraph.
The final message should look like: "The main text is this one with bold text near, add me near the other paragraph without losing the dynamic content."
How can I achive this? I can't use innerText/innerHTML, appendchild and I can't harcode the paragraph with the dynamic content. Many thanks.
Without innerText, innerHTML and DOM manipulation functions there is not really any way to change the document?
I am assuming that you can use them, but that you've not managed to make it work?
Please add more detail to your question if this is not the case.
Without knowing what your desired markup is, I've just removed all the p.paragraph and replaced them with a textNode with their innerText. Also setting the display: inline to p.bold-dynamic to remove the new line(s)
I've updated the code to now just insert lots of display: inline
// find all p.paragrah inside div.text
document.querySelectorAll("div.text > p.paragraph").forEach((element) => {
// insert a textNode with the innerText of the p.paragraph
//element.parentNode.insertBefore(document.createTextNode(element.innerText), element)
// set p.bold-dynamic display: inline
//element.parentNode.querySelector("p.bold-dynamic").setAttribute("style", "display: inline;")
// remove the p.paragraph
//element.parentNode.removeChild(element)
element.setAttribute("style", "display: inline;")
element.querySelectorAll("*").forEach((tag) => {
tag.setAttribute("style", "display: inline;")
})
element.parentNode.querySelector("p.bold-dynamic").setAttribute("style", "display: inline;")
})
<div class="text">
<p class="paragraph">
<span>The main text is this one </span>
<span class="bold">with bold text near</span>
</p>
<p class="bold-dynamic" style="" data-message-code="dynamic-message">Add me near the other paragraph without losing the dynamic content</p>
</div>
<div class="text">
<p class="paragraph">
<span>The main text is this one </span>
<span class="bold">with bold text near</span>
</p>
<p class="bold-dynamic" style="" data-message-code="dynamic-message">Add me near the other paragraph without losing the dynamic content</p>
</div>
<div class="text">
<p class="paragraph">
<span>The main text is this one </span>
<span class="bold">with bold text near</span>
</p>
<p class="bold-dynamic" style="" data-message-code="dynamic-message">Add me near the other paragraph without losing the dynamic content</p>
</div>

Using jQuery to add paragraph tags and skip HTML elements

I have some HTML being fed in to me for blogs and want to be able to ensure it's parsed properly.
I am using this jQuery function (below) to ensure text is being wrapped in a paragraph tag however it seems to be filtering out the strong and a tags into their own paragraph tags.
Here is the original HTML:
<div id="demo">
<h2>This is a title</h2>
This is content that will need to be wrapped in a paragraph tag <strong>and this is bold</strong> and this is a link.<br />
More content here.
</div>
Now using this function to filter this:
$('#demo')
.contents()
.filter(function() {
return this.nodeType === 3 && $.trim(this.textContent).length;
})
.wrap('</p>');
Renders me this HTML:
<div id="demo">
<h2>This is a title</h2>
<p>This is content that will need to be wrapped in a paragraph tag </p>
<strong>and this is bold</strong>
<p> and this is a </p>
link.
<p>More content here.</p>
</div>
As you can see, I'm getting half of what I need but it's separating the HTML elements outside of the paragraph tag. Is there a way I can allow these HTML elements to remain inside the paragraph tag?
Thanks
You can store the h2 element, remove it from the structure, wrap what remains and add back in the h2.
let cloned = $("#demo > h2").clone(); // Clone the <h2>
$("#demo > h2").remove(); // Remove the <h2>
$("#demo").wrapInner("<p>"); // Wrap everyting left over
cloned.insertBefore("p"); // Put <h2> back
console.log($("#demo").html());
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="demo">
<h2>This is a title</h2>
This is content that will need to be wrapped in a paragraph tag <strong>and this is bold</strong> and this is a link.
More content here.
</div>

JavaScript: Replacing (all) certain words on a web page

I am having trouble with some code for a chrome extension. The code is supposed to replace a word with another one. It does this, however, I would only like it to replace a word if it is within certain tags such as <p></p> or header tags. At the moment it replaces all the words in the HTML file within the <body></body>. This sometimes interferes with the HTML code and can break certain features of a website. Here's what I have currently.
document.body.innerHTML = document.body.innerHTML.replace(newRegExp("old", "g"), "new");
Thank you for the help!
So just loop over all the elements that you care about and do the replacement on those elements only.
// Get all the elements that you care about into an array
let elements = Array.prototype.slice.call(document.querySelectorAll("p, header"));
// Loop over the items in the array
elements.forEach(function(el){
// Do the replace on the element
el.textContent = el.textContent.replace(/text/g, "letters");
});
<header>This is some text in a header</header>
<h1>This is some text in an h1</h1>
<div>This is some text in a div</div>
<p>This is some text in a p</p>
<div>This is some text in a div</div>
<div>This is some text in a div
<p>This text is inside of a p with lots of text</p>
</div>

How to retrieve tag plain text inside a nested tag

I have a HTML page and I want to retrieve a tag's plain text which is in another tag using JavaScript.
<div id="article_content">
<p>paragraph 1 </p>
<p>paragraph 2 </p>
<p>paragraph 3 </p>
</div>
So basically I want to retrieve all of the <p> plain text. Please help
On a side note: I'm incorporating my JavaScript in android studio.
You could use .textContent of the parent node to get the text.
alert(document.querySelector('#article_content').textContent)
<div id="article_content">
<p>paragraph 1 </p>
<p>paragraph 2 </p>
<p>paragraph 3 </p>
</div>
You can try using:
arr = document.getElementById("article_content").children;
for(var i = 0; i < arr.length; i++)
console.log(arr[i].innerHTML);
document.getElementById("article_content") returns an object representing the tag with id "article_content".
.children member function returns all the elements of the tag with id "article_content" as an HTML collection.
Then use .innerHTML to access the content of the <p> tags inside the div with id "article_content".
More useful information on this can be found at http://www.w3schools.com/jsref/dom_obj_all.asp
You can use $("#article_content").text() to get the contents as text.

How to find and unwrap elements from their parent?

So simply, I am trying to find and unwrap elements on my page. There is a slight problem going wrong with my WYSIWYG editor, and I need to apply a fix.
For example:
This is how my HTML currently looks like
<h1>
<p>Some text here</p>
<p>Some text here</p>
<p>Some text here</p>
<img src="images/img.jpg" />
</h1>
<h1>
<p>Some text here</p>
<p>Some text here</p>
</h1>
This how how my HTML should look like
<p>Some text here</p>
<p>Some text here</p>
<p>Some text here</p>
<img src="images/img.jpg" />
<p>Some text here</p>
<p>Some text here</p>
How can I completely remove the h1 tag?
This is my attempt. I am running this once the entire page has been loaded.
if ($('h1').find('p').length) {
$('p', this).unwrap();
}
PS. This always occurs at random, there is no pattern. Can sometimes happen to many elements, and sometimes only to a few.
you can select the children of h1 and unwrap them like
$('h1 > *').unwrap();
var $h1 = $('h1');
$h1.contents().unwrap();
$h1.remove()
Demo: Fiddle
Note: the value referred by this will not change inside the if condition - from the way use have used it I assume you are thinking this inside the if block is referring to the h1 element
You can use .replaceWith():
$('h1').replaceWith(function() { return $(this).find('*'); });
Fiddle Demo

Categories

Resources