How can i add multi lines together into different different div / span tag through this text box? - javascript

How can i add multi lines together into different different span tag through this text box ?
There is an text box, by using this box i can insert a new div / span class content Right ?
But every time when i need to add new class i need to write a new line in this text box and need to press send button, Now i want that if i have 10 lines content together with "Enter" button line break
Like
My Line 1 is here
My Line 2 is here
My Line 3 is here
My Line 4 is here
My Line 5 is here
My Line 6 is here
My Line 7 is here
My Line 8 is here
... and so on
then i want to paste all 10 lines in this text box together and by pressing send button i want that all lines must be add in different different div / span class not all in one class with < br > tag that is working now.
so plz help me to improve my code
Love you Helper and Thanks in Advance
const sendButton = document.getElementById('send-btn');
const textArea = document.getElementById('input');
const innerDiv = document.getElementById('inner');
var message = textArea.value;
sendButton.addEventListener('click', function () {
const message = new MessageContainerBuilder().BuildMessage(textArea.value);
innerDiv.appendChild(message);
textArea.value = '';
});
function encodeHtmlEntity(input) {
var output = input.replace(/[\u00A0-\u9999<>\&]/gim, function (i) {
return '&#' + i.charCodeAt(0) + ';';
});
return output;
}
function MessageContainerBuilder() {
var createDivElement = function (classTest) {
var div = document.createElement('div');
var classAttr = document.createAttribute('class');
classAttr.value = classTest;
div.setAttributeNode(classAttr);
return div;
};
var createSpanElement = function (value, classTest) {
var span = document.createElement('span');
if (classTest) {
var classAttr = document.createAttribute('class');
classAttr.value = classTest;
span.setAttributeNode(classAttr);
}
span.innerText = encodeHtmlEntity(value);
return span;
};
this.BuildMessage = function (text) {
var divContainer = createDivElement('outgoing');
var messageSpan = createSpanElement(text, 'me');
divContainer.appendChild(messageSpan);
return divContainer;
};
}
<div id="inner">
<div class="incoming">
<div class="them">Lorem
</div>
</div>
<div class="outgoing">
<div class="me">Lorem ipsum
</div>
</div>
</div>
<textarea class="input" id="input" placeholder="Message..."></textarea>
<button class="waves-effect waves-light" id="send-btn">Send</button>
so plz help me to improve my code
Love you Helper and Thanks in Advance

I took some liberties and simplified your code as you can see below. It does everything I believe your code was attempting.
Note that I'm using .split("\n") to break your input based on each newline character and then iterate over that as necessary.
Also, you said you were inserting a div/span, but I don't see your code actually creating a span tag. I wrote my code to do that for you though.
const sendButton = document.getElementById('send-btn');
const textArea = document.getElementById('input');
const innerDiv = document.getElementById('inner');
var message = textArea.value;
sendButton.addEventListener('click', function() {
// split the textarea entries into an array
let lines = (textArea.value).split("\n");
// iterate over each line, creating a div/span and inserting into the DOM
lines.forEach( (line) => {
let encodedLine = encodeHtmlEntity(line);
let newElement = `<div class="me"><span>${encodedLine}</span></div>`;
innerDiv.innerHTML += newElement;
});
// reset the textarea
textArea.value = '';
});
function encodeHtmlEntity(input) {
var output = input.replace(/[\u00A0-\u9999<>\&]/gim, function(i) {
return '&#' + i.charCodeAt(0) + ';';
});
return output;
}
<div id="inner">
<div class="incoming">
<div class="them">Lorem
</div>
</div>
<div class="outgoing">
<div class="me">Lorem ipsum
</div>
</div>
</div>
<textarea class="input" id="input" placeholder="Message..."></textarea>
<button class="waves-effect waves-light" id="send-btn">Send</button>

You can try using String.prototype.split() so that each text is separated by \n (new line) into an array, then you can iterate over each element like using Array.prototype.forEach(). Here's the code you can use:
sendButton.addEventListener('click', function () {
textArea.value.split('\n').forEach((text) => {
const message = new MessageContainerBuilder().BuildMessage(text);
innerDiv.appendChild(message);
});
textArea.value = '';
});

Related

How to copy and paste HTML/text by JavaScript

I want to copy a text that has the CSS class copytext
and want to paste on the same page that's has CSS class pastehere.
I am using the following code, but with no result.
function copyToClipboard(text) {
const elem = document.createElement('.copytext');
elem.value = text;
document.body.appendChild(elem);
elem.select();
document.execCommand('.pastehere');
document.body.removeChild(elem);
}
I think you want to get the value of an HTML tag or something? with DOM Element innerHTML you can get the value of the Tag. eg:
html:
`<p id="myTag">hello world</p>`
javascript:
`let var1 = document.getElementById("myTag").innerHTML;`
the 'hello world' is now stored in the variable 'var1' and you can continue to work with it normally
If you want to copy text from all elements .copytext to the element .pastehere:
HTML:
<div class="copytext">Line 1</div>
<div class="copytext">Line 2</div>
<div class="copytext">Line 3</div>
JS:
function fun(text){
let copiedText = "";
text.forEach(element => {
copiedText += element.textContent + "\n";
});
const resault = document.createElement('div');
resault.classList.add('pastehere');
resault.innerText = copiedText;
document.body.appendChild(resault);
}
let copyFrom = document.querySelectorAll('.copytext');
fun(copyFrom);
You'll get:
<div class="pastehere">
Line 1 <br>
Line 2 <br>
Line 3 <br>
</div>
If you want to create element with the text you pass to the function as an argument:
JS:
function fun(text){
let resault = document.createElement('div');
resault.classList.add('pastehere');
resault.innerText = text;
document.body.appendChild(resault);
}
let text = "My text";
fun(text);
You'll get:
<div class="pastehere">
My text
</div>
!! Note that you can only type a tag name in document.createElement('');
You can use
document.getElementById("ID NAME")
To copy.
To change you can use
document.getElementsByClassName("class-name").style[0] = "max-width: 10%;"

Covert html in javascript to HTML tags

I'm working on the tooltips and from the backend I'll get data in with html tags. I need to show in the tooltip with its corresponding data in its respective tags. For example, I'll get hello user click here from the backend. I've to show as hello user in h1 format and click here should be a anchor. I tried with both functions and replace its not working.
With function:
<h1 id="data">
</h1>
function convertToPlain(html){
var tempDivElement = document.createElement("div");
tempDivElement.innerHTML = html;
return tempDivElement.textContent || tempDivElement.innerText || "";
}
var htmlString= "<div><h1>Bears Beets Battlestar Galactica </h1>\n<p>Quote by Dwight Schrute<a> click here<a></p></div>";
let dataVal = convertToPlain(htmlString)
document.getElementById("demo").innerHTML = dataVal;
With replace:
https://codesandbox.io/s/serene-fast-u8fie?file=/App.svelte
I made below snippet by copy-paste your code and just update return statement inside convertToPlain function, also I added href attribute to <a> in the htmlString content.
function convertToPlain(html) {
var tempDivElement = document.createElement("div");
tempDivElement.innerHTML = html;
return tempDivElement.innerHTML;
}
var htmlString = "<div><h1>Bears Beets Battlestar Galactica </h1>\n<p>Quote by Dwight Schrute<a href='#'> click here<a></p></div>";
let dataVal = convertToPlain(htmlString)
document.getElementById("demo").innerHTML = dataVal;
<h1 id="demo"></h1>

How can I add a span to h3 Element with javascript

I'm making a chat and I want to add an avatar pics feature so I figured it might work well with span, but the problem is I don't know how to add the span to the element.
let avatar = document.createElement("span");
let userMessage = document.createElement("H3");
avatar.setAttribute(userMessage);
userMessage.innerHTML = username + ": " + message;
//document.getElementById("chat").appendChild(avatar);
document.getElementById("chat").appendChild(userMessage);
userMessage.style.background = color;
userMessage.style.textAlign = "left";
document.getElementById("msg").value = "";
I am assuming that you have div with id="chat" and you want to append an h3 tag in a span and then append the chat div so your code will look like this
var username="zulqarnain jalil";
var message ="welcome back, have a nice day";
var color='lightgrey';
var avatar = document.createElement("span");
var userMessage = document.createElement("h3");
userMessage.innerHTML = username + ": " + message;
userMessage.style.background = color;
userMessage.style.textAlign = "left";
avatar.appendChild(userMessage);
document.getElementById("chat").appendChild(avatar);
//document.getElementById("msg").value = "";
<div id="chat">
</div>
I have created a chatbot snippet for you, here you can test it
var username="zulqarnain jalil";
function sendMessage()
{
var message =document.getElementById('messagebox').value;
if(message)
{
document.getElementById('messagebox').value='';
var color='lightgrey';
var avatar = document.createElement("span");
var userMessage = document.createElement("h3");
userMessage.innerHTML = username + ": " + message;
userMessage.style.background = color;
userMessage.style.textAlign = "left";
avatar.appendChild(userMessage);
document.getElementById("chat").appendChild(avatar);
}
else
{
// message empty
}
}
//document.getElementById("msg").value = "";
<div id="chatBox">
<div id="chat">
</div>
<div>
<input type="text" id="messagebox" />
<input type="button" onclick="sendMessage()" value="Send" />
</div>
</div>
First you need to add the span as a child of the H3 element.
I think the best approach to this problem is creating a class Message. Initializing that class creates h3 and span with unique ids stored in a variable id for future use. The class will also add the h3 as a child of it's parent element ( what ever it is ), and the span as a child of the h3 element.
var counterText = 0;
var counterAvatar = 0;
class UserMessage {
constructor(msgTxt, avatar){
// This block initializes the text message of the user
// It will also add an id to the tag for future use
let msgTxt = document.createTextNode(msgTxt);
this.messageID = 'text' + counterText;
this.message = document.createElement('h3');
this.message.appendChild(msgTxt);
this.message.setAttribute('id', this.messageID);
counterText++;
// This block creates an img element with the attributes src and id
this.avatarID = 'avatar' + counterAvatar;
this.avatar = document.createElement('img');
this.avatar.setAttribute('src', avatar);
this.avatar.setAttribute('id', this.avatarID);
counterAvatar++;
// This block appends the avatar element to the text and the text to the
// chat div.
let chat = document.getElementById('chat');
this.message.appendChild(this.avatar);
chat.appendChild(this.message);
}
}
to initialize a new instance:
var message = new UserMessage("Hello, this is a text message!",'<path/to/avatar>')
this is an object oriented aproach.
you could also just append the avatar to the message and the message to the chat.
But I think aproaching the problem in an object oriented way is much better since it will save time in the future when you're updating your app.
Markdown works fine in here.
Block-level HTML elements have a few restrictions:
They must be separated from surrounding text by blank lines.
The begin and end tags of the outermost block element must not be indented.
Markdown can't be used within HTML blocks.

How to replace more than one word in JavaScript string at a same time?

I have a javascript string that contains some code like [Hover on me](Tooltip text). I want to convert this code to HTML. [] containing text and () containing tooltip text
Here is what I want
<div class="tooltip">Hover over me
<span class="tooltiptext">Tooltip text</span>
</div>
The string contains multiple tooltip codes and I need to convert each of them to this HTML code
what I am trying
<p id="p">blabla [some info](tool) it is text [one](tool) [two] (tool)</p>
var text = document.getElementById('p').innerHTML;
var matches = text.match(/\[(.*?)\]/);
var final = text.match(/\((.*?)\)/);
var res = text.replace(matches[0], "<span>"+matches[1]+"</span>");
var newtext = document.getElementById('p').innerHTML = res;
var ros = newtext.replace(final[0], "<span>"+final[1]+"</span>");
document.getElementById('p').innerHTML = ros;
console.log(ros);
I know the code is pretty messed up but I need some help with this. I was also trying other code as well but that didn't work either, here is fiddle https://jsfiddle.net/mohitchandel/aszv8w93/10/
var text = document.getElementById('p').innerHTML;
// You may want to validate this loop better.
while( text.indexOf(')') > 0 ) {
let a = text.slice( text.indexOf('[') + 1, text.indexOf(']') ),
b = text.slice( text.indexOf('(') + 1, text.indexOf(')') ),
c = `<div class="tooltip">${ a } <span class="tooltiptext">${ b }</span></div>`;
text = text.slice( 0, text.indexOf('[') ) + c + text.slice( text.indexOf(')') + 1 );
}
This could get you started.
--
RMZ

Replace certain text automatically with an image

I'm currently creating a small website and I want to automatically replace certain text with an image without a press of a button. I want it done automatically, but I can't seem to make it work. Thank you!
Here's my code:
html
<p id="test">http://localhost:1111/</p>
javascript:
<script>
var str = document.getElementById("test").innerHTML;
var res = str.replace("http://localhost:1111", Element.innerHTML = "<img
src='https://www.stockgumshoe.com/wp-content/uploads/2014/06/test.jpg");
document.getElementById("demo").innerHTML = res;
</script>
For this code you don't need any id or class
const paragraphs = document.querySelectorAll('p')
paragraphs.forEach((paragraph) => {
if (paragraph.innerText == 'http://localhost:1111/') {
return (paragraph.innerHTML = `
<img src='https://www.stockgumshoe.com/wp-content/uploads/2014/06/test.jpg' />
`)
}
})
Instead of this:
<script>
var str = document.getElementById("test").innerHTML;
var res = str.replace("http://localhost:1111", lement.innerHTML = "<img
src='https://www.stockgumshoe.com/wp-content/uploads/2014/06/test.jpg");
document.getElementById("demo").innerHTML = res;
</script>
Try This:
<script>
document.getElementById("test").innerHTML = `<img
src="https://www.stockgumshoe.com/wp-content/uploads/2014/06/test.jpg" />`;
</script>

Categories