How can I append new "p" element with formatted text - javascript

I have a javascript function designed to dynamically append text to my document (and slides it down with JQuery). I create a new "p" element, and then I want to add text to it, but I need this text to have several formats. For example, I need the first part to be italicized, second part to be underlined, and third part to be white. As of now, I managed to get three different "div" elements with their own text nodes, each with their own style, but this makes it on three separate lines. I need it all on one line. Is there any way I can insert HTML tags into a text node, or somehow split the internal string up so I can style each part separately?
This code demonstrates the closest I got, but this puts each styled text node on different lines, and I need it all on one line in that p element:
function append_announcement(time_string, user_by, text){
newp = document.createElement("p");
head = document.createElement("span");
headt = document.createTextNode("You wrote: ");
head.appendChild(headt);
body = document.createElement("div");
bodyt = document.createTextNode(text);
body.appendChild(bodyt);
body.setAttribute("style", "color: white");
foot = document.createElement("div");
foott = document.createTextNode("Done.");
foot.appendChild(foott);
newp.appendChild(head);
newp.appendChild(body);
newp.appendChild(foot);
newp.setAttribute("align", "center");
newp.style.display = "none";
document.getElementById("announcement_posts").insertBefore(newp,
document.getElementById("announcement_posts").firstChild);
$("p").slideDown("slow");
}

Change the <div>s for <span>s, they're displayed inline by default.
Alternatively you could apply a class to the <div> elements you create and set that class to display: inline-block; using CSS.

Example
function append_announcement(time_string, user_by, text){
newp = document.createElement("p");
var i = document.createElement("i");
i.textContent = ("You wrote ");
var span = document.createElement("span");
span.textContent = text;
span.style.color = "white";
var u = document.createElement("u");
u.textContent = " Done.";
newp.appendChild(i);
newp.appendChild(span);
newp.appendChild(u);
newp.setAttribute("align", "center");
newp.style.display = "none";
document.getElementById("announcement_posts").insertBefore(newp,
document.getElementById("announcement_posts").firstChild);
$("p").slideDown("slow");
}
You want to create elements that display inline like <i>, <u> or <span>

Related

Change color of specific part of element string in JavaScript

I'm creating a chat application, and I want the users text's to be colored. Here is how I create the text element:
var item = document.createElement('li');
item.textContent = `[Anye]: hello`;
item.style.fontWeight = 'bold';
item.style.color = 'red';
This is how this code is executed:
This, on the other hand, is what I would want:
Is there a way that I can change the color of only part of the text?
Note: The desired image was created using the console, and please keep in mind that the messages are not fixed, it's up to the user what they want to say.
I'm willing to use jQuery for this example, if needed.
Thanks!
You can wrap the author in a span element and set style property.
var item = document.createElement('li');
item.style.fontWeight = 'bold';
const author = document.createElement("span");
author.innerText = "[Anye]: ";
author.style.color = 'red';
item.append(author);
item.innerHTML += "hello";
document.body.append(item);
Or you can wrap the message in a span element and set a predefined style in CSS.
var item = document.createElement('li');
item.innerHTML = `[Anye]: <span>hello</span>`;
item.style.fontWeight = 'bold';
item.style.color = 'red';
document.body.append(item);
li span {
color: initial;
}

How can I write down paragraphs in HTML with Javascript without the use of getElementbyId?

So, i was working on this little formatting experiment with HTML, where you could create a paragraph via input and it would create an HTML paragraph on the screen. I did it by doing this.
HTML:
<button onclick="create_para()">Create Paragraph</button>
<p id="p1"></p>
Javascript:
function create_para(){
var p = window.prompt("Enter paragraph text: ");
document.getElementById("p1").innerHTML = p;
}
And, it worked! The only problem is that I wanted it so you could click the button again and again and it would create new paragraphs without replacing the old one. The only way I thought I could do it would be by making a bunch of tags with different classes, and having a bunch of functions, and a lot of buttons, but that's inefficient and too complicated.
So, I found out about document.write() and document.writeln(). So I used it in my code, but turns out it just deletes all other HTML code and just leaves it with the lines I wrote.
Therefore, is the a form of writing down paragraph lines without the use of ID's, or a form where it wouldn't delete all HTML code?
Thanks.
You can do something like:
function create_para(){
var p = window.prompt("Enter paragraph text: ");
var elem = document.createElement('p');
elem.innerText = p;
document.body.appendChild(elem)
}
EDIT: to add an id to each, you can add a global counter variable.
var i = 0;
function create_para(){
var p = window.prompt("Enter paragraph text: ");
var elem = document.createElement('p');
elem.innerText = p;
elem.id = '' + i;
i++;
document.body.appendChild(elem);
}
You can create a div container and then creates HTML Elements dinamically with your function, also you can assing an id to your new element, try this:
let div = document.getElementById('container');
function create_para(){
let p = document.createElement('p');
let txt = window.prompt("Enter paragraph text: ");
p.textContent = txt;
p.id = 'your id';
div.appendChild(p);
}
<div id='container'></div>

find closing anchor tag from the string and add some value

I am trying to find closing anchor tag. And add Icon after the closing tag.The inside value is coming as a string from database.I need to extract the value and append with icon.
For example
<p>This is a paragraph and link testtestdsfasffdtest1fdfdfdfdfd</p>
In the above example I have paragraph tag inside I have two anchor tag.
Actually the result will come as Test added plus icon testdsfasffd & Test1 added plus icon 2 fdfdfdfdfd
First I need to find the closing anchor tag then i need to append the icon from other functions
Current I am trying like this
var string = '<p>This is a paragraph and link testtestdsfasffdtest1fdfdfdfdfd</p>';
I am setting an pattern
var closingAnchor = '</a>';
string.split(closingAnchor);
after this i need to append icon from other function using for loop. I am getting struggle here kindly please help me.
Splitting HTML is normally a bad bad idea. So just do it with the DOM.
var string = '<p>This is a paragraph and link testtestdsfasffdtest1fdfdfdfdfd</p>';
var div = document.createElement("div");
div.innerHTML = string;
var anchors = div.getElementsByTagName("a");
for (var i = 0; i < anchors.length; i++) {
var text = document.createTextNode(' TEXT TO ADD ');
var sibling = anchors[i].nextSibling;
if(sibling) {
anchors[i].parentNode.insertBefore(text, sibling);
} else {
anchors[i].parentNode.appendChild(text);
}
}
console.log(div.innerHTML);
document.getElementById("out").innerHTML = div.innerHTML;
<div id="out"></div>
Here you are: // for regex, <\/a> for </a>, g for search all
var string = '<p>This is a paragraph and link testtestdsfasffdtest1fdfdfdfdfd</p>';
var output = string.replace(/<\/a>/g, '</a>YOUR APPENDEE');
alert(output);
Hope this helps.

How do I create an element from html formatted text?

I'm using Angular 1.29 and Chrome.
I have some text like
<p>Text <strong> bold </strong> </p>
And I need to turn it into an element, because the library that I'm using, html2canvas, needs to be sent one.
So I've tried this, which I took from this answer
var div = document.createElement('div');
div.innerHTML = $scope.presData.text;
var element = div.firstChild;
html2canvas(element,{
onrendered:function(newCanvas){
document.getElementById("newPresentation").appendChild(newCanvas);
}
});
Where my text is in $scope.presData.text,
But that didn't work. This creates a canvas with a width and height of 0.
Using innerHTML of an HTML element should format them as document nodes.
var HTMLString = '<p>Text <strong> bold </strong> </p>';
var HTMLStringContainer = document.createElement('div');
HTMLStringContainer.innerHTML = HTMLString;
If you're having some issues with your canvas, I think your issue lies elsewhere.
Try this to set up your strings as html nodes... it is robust and will handle alot of different situation (multiple sibling nodes at the highest level for example). jsfiddle Demo
// HTML string
var s = '<p>Text <strong> bold </strong> </p>';
var div = document.createElement('div');
div.innerHTML = s;
var elements = div.childNodes;
//using your above canvas code
var element = elements[0];
html2canvas(element,{
onrendered:function(newCanvas){
document.getElementById("newPresentation").appendChild(newCanvas);
}
});
//multiple elements
//for(var i=0; i < elements.length; i++){
//html2canvas(elements[i],{
//onrendered:function(newCanvas){
//document.getElementById("newPresentation").appendChild(newCanvas);
//}
//});
//}

How can I make text bold with nodes and .createElement("b")?

I have to make text bold if I click on a button using nodes and createElement but I don't really know how...
html (This is the text I want to make bold):
<p id="textalt">Dies ist ein Text in einem P-Tag</p>
javascript:
function fettmachen(){
var neuB = document.createElement("b");
document.getElementById("textneu").insertBefore(neuB, document.getElementById("textneu").nextSibling);
}
I don't know how it works.
"I have to do it with nodes and createElement"
function fettmachen(){
// create the "b" element
var neuB = document.createElement("b");
// fetch the "textneu" element by ID
var textneu = document.getElementById("textneu");
// append the firstChild of "nextneu" to the "neuB"
neuB.appendChild(textneu.firstChild);
// append the "neuB" to the "nextneu"
nextneu.appendChild(neuB);
}
I suggest, instead of adding new tags, just use CSS, and add a class to the element.
CSS:
.boldText{
font-weight: bold;
}
JavaScript:
function fettmachen(){
document.getElementById("textalt").className += ' boldText';
}
I'd just put a style on the <p> tag on the button press. Maybe something like...
function fettmachen(){
var neuB = document.getElementById("textalt");
neuB.style.fontWeight = "bold";
}
Well, you could use the following code. It's longer and could be condensed - I find it clearer to read, personally.
function fettmachen()
{
var pElem = document.getElementById('textAlt');
var text = pElem.innerHTML;
var bElem = document.createElement('b');
bElem.innerHTML = text;
pElem.innerHTML = '';
pElem.appendChild(bElem);
}
This is how you make the text bold
function fettmachen(){
var p = document.getElementById("textneu");
p.style.fontWeight = "bold;"
}
If you have to use js for some reason for instance you need to only bold certain words maybe, and don't have access to the style sheet here you go. Otherwise use what Rocket has suggested.
Seriously only use a solution like this if at some point you will need to only bold certain words, or groups of words within an element.
function fettmachen(){
var neuB = document.createElement("b"),
textEl = document.getElementById("textalt"),
text = textEl.textContent;
neuB.textContent = text;
textEl.textContent = "";
textEl.appendChild(neuB);
}
Live Demo
And to unbold.
function unbold(){
var textEl = document.getElementById("textalt"),
boldEls = textEl.getElementsByTagName("b"),
text = "";
for(var i = 0; i < boldEls.length; i++){
text+=boldEls[i].textContent;
textEl.removeChild(boldEls[i]);
}
textEl.textContent = text;
}
Live Demo 2

Categories