So I want to write out the text inside input value item and make a another node to right of the text. But this text just shows [object HTMLParagraphElement] next to the text in the input, why doesnt it shows the text?
I dont know what I do wrong, please help me!
so the text from the input is showed but not the other p element I made?
Here is the code:
var lista = document.getElementById("lista");
var li = document.createElement("li");
var del = document.createElement("p");
var delt = document.createTextNode("remove this");
del.appendChild(delt);
var item = document.getElementById("item");
var text = document.createTextNode(item.value + " | " + del);
li.appendChild(text);
lista.appendChild(li);
You don't need to create text nodes to append the text. Just set the innerHTML on the elements you are creating:
var myPar = document.createElement('p');
myPar.innerHTML = "remove this";
li.innerHTML = myPar.outerHTML; //this would be the tag and its text <p>remove this</p>
// other code here.
Demo Fiddle
the problem is the line
var text = document.createTextNode(item.value + " | " + del);
at this time ,the 'del' referenced a paragraph element,
you could have "del.innerHtml" instead of 'del'
Change your code to use del.innerHTML.
var text = document.createTextNode(item.value + " | " + del.innerHTML);
the argument of document.createTextNode must be a string.And the innerHTML is the html code of a element object.
http://jsfiddle.net/4YgXG/
HTML:
<ul id="lista"></ul>
Js:
// EXAMPLE!
var lista = document.getElementById("lista");
var item = document.getElementById("item");
for(var i=0;i<100;i++){
var li = document.createElement("li");
var del = document.createElement("p");
del.innerHTML = 'Remove this';
li.appendChild( del );
lista.appendChild(li);
}
Related
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.
I am trying to create an li element in my html code via javascript. This li will have an onclick function. The problem is that trying to pass a file path as an argument in the loadDoc2() function, some problems occur. I am including the code.
function myFunction(){
var x = "NEW";
var file = "'/static/BRANDS/PERLA/NEW COL/XML Files/NEW COL.xml'";
lis = "<li><a onclick='loadXMLDoc2(" + file + ")'>" + x + "</a></li>";
document.getElementById("demo").innerHTML = lis;
}
This gives me <a onclick="loadXMLDoc2(" static brands perla new col xml files new col.xml')'>NEW</a>. The slashes are replaced by spaces and letters are low case. The result that I need is <a onclick="loadXMLDoc2('/static/BRANDS/PERLA/NEW COL/XML Files/NEW COL.xml')">NEW</a>
I have tried many things such as .replace("\", "//") but it didn't work.
This happens because you start your onclick with ' and file has a ' at the start, so it closes the onclick attribute. So it looks like
<li><a onclick='loadXMLDoc2('/static/BRANDS/PERLA/NEW COL/XML Files/NEW COL.xml')'>NEW</a></li>
I suggest you use javascript to bind the event, it's gonna be way easier.
function myFunction(){
var x = "NEW";
var file = "/static/BRANDS/PERLA/NEW COL/XML Files/NEW COL.xml";
var li = document.createElement('li');
var a = document.createElement('a');
a.innerHTML = x;
a.onclick = function(){
loadXMLDoc2(file);
}
li.appendChild(a);
document.getElementById("demo").appendChild(li);
}
<div id="container"></div>
<script>
var container = document.getElementById('container');
var li = document.createElement('li');
li.innerText = "Im a list item";
li.onclick = function(){
console.log('I was clicked');
}
container.appendChild(li);
</script>
you appear to have conflicting quotes.
lis === "<li><a onclick='loadXMLDoc2('/static/BRANDS/PERLA/NEW-COL/XML-Files/NEW COL.xml')'>NEW</a></li>"
note that k='loadXMLDoc2('/ will open then close the quotes. fixed by changing single to double quotes:
var x = "NEW";
var file = "'/static/BRANDS/PERLA/NEW-COL/XML-Files/NEW COL.xml'";
lis = `<li><a onclick="loadXMLDoc2(${file})">${x}</a></li>`;
document.body.innerHTML = lis;
My ToDo List dont wanna work the way i want. I've just been working with JavaScript for 2 weeks sthis is very new to me, therefor the code maybe doesnt look that nice.
The result comes out wrong. If I type in "buy food" the first line gonna show just that, but the next time I wanna add "walk the dog", then it displays
buy food
buy food
walk the dog
I hope you understand my problem. It also ends the unordered list tag after the first click and adds the rest of the things in another.
Here's the JavaScript:
var taskList = [];
var text = "<ul>"
function addToList() {
var task = document.getElementById("toDoTask").value;
taskList.push(task);
for(i = 0; i < taskList.length; i++){
text += "<li>" + taskList[i] + "</li>" ;
}
text += "</ul>";
document.getElementById("todoList").innerHTML = text;
}
The issue is you're closing the ul tag after adding each item. Instead of concatenating raw HTML, consider using element objects and appending, and using a text node object to handle the user input - this removes the possibility of a DOM Based XSS vulnerability.
window.onload = function() {
var taskList = [];
var container = document.getElementById("todoList");
document.getElementById("add").onclick = addToList;
function addToList() {
var task = document.getElementById("toDoTask").value;
taskList.push(task);
var ul = document.createElement('ul');
var li;
for (i = 0; i < taskList.length; i++) {
li = document.createElement('li');
li.appendChild(document.createTextNode(taskList[i]))
ul.appendChild(li);
}
container.innerHTML = '';
container.appendChild(ul);
}
};
Task:
<input id="toDoTask" /> <input type="button" id="add" value="Add" />
<div id="todoList">
</div>
You should not use the innerHtml. This replace all the text of your content. You should just add the li to your ul.
You can do that by using the append function by jquery Append
your <ul> must contain an id like this <ul id="toDoList">
then you make $("#toDoList").append("yourTask");
yourTask must contains the li.
With this, you don't need to iterate on all your element list
Not sure, but you seem to keep adding to text the second time, so text will be something like <ul><li>buy food</li></ul><li>buy food</li><li>walk the dog</li></ul>, which is invalid HTML by the way, but gets outputted anyway...
On each call of function addToList() you should reset the variable text.
For example:
function addToList() {
var task = document.getElementById("toDoTask").value;
taskList.push(task);
text="";
for(i = 0; i < taskList.length; i++){
text += "<li>" + taskList[i] + "</li>" ;
}
text += "</ul>";
document.getElementById("todoList").innerHTML = text;
}
The whole list of items in array will appends to variable text on each call.
Here is my code for my current todo list.
<html>
<head>
<title>ToDo</title>
</head>
<body>
<script>
function addText(){
var input = document.getElementById('input').value;
var node = document.createElement("P");
var textnode = document.createTextNode(input);
node.appendChild(textnode);
document.getElementById('do').appendChild(node);
}
</script>
<p id="do"> </p>
<input type='text' id='input'/>
<input type='button' onclick='addText()' value='Add To List'/>
</body>
</html>
It works to add objects but I have no idea what the javascript is to remove objects?
I wonder if someone could help me with a remove script like a X mark on the side of a new added object or something just to remove 1 after you add it,
Cheers
I think I found a solution to your problem. Check my fiddle:
http://jsfiddle.net/Kq4NF/
var c = 1;
function addText(){
var input = document.getElementById('input').value;
var node = document.createElement("P");
node.setAttribute('id', 'anchor'+c);
var textnode = document.createTextNode(input);
node.appendChild(textnode);
var removenode = document.createElement("input");
removenode.setAttribute('type', 'button');
removenode.setAttribute('value', 'X');
removenode.setAttribute("onclick", "removeText('anchor"+c+"')");
node.appendChild(removenode);
c++;
document.getElementById('do').appendChild(node);
}
function removeText(item){
var child=document.getElementById(item);
document.getElementById('do').removeChild(child);
}
Good luck!
var list = document.getElementById("do");
list.removeChild(list.childNodes[0]);
list - represents the p tag with ID do
list.ChildNodes - list of child elements appended to your p tag with ID as do.
list.ChildNodes[0] - represents the first child appended to the list, where 0 is the index.
To remove a specific element, either represent the is as index or point directly the element like
var list = document.getElementById("do");
var node = document.createElement("P");
var textnode = document.createTextNode(input);
textnode.id = "do1"; // Add id to the child element
node.appendChild(textnode);
document.getElementById('do').appendChild(node);
// This is to remove it using ID
list.removeChild(document.getElementById("do1"));
Hope you can understand.
var theNewParagraph = document.createElement('p');
var theBoldBit = document.createElement('b');
var theBR = document.createElement('br');
theNewParagraph.setAttribute('title','The test paragraph');
var theText1 = document.createTextNode('This is a sample of some ');
var theText2 = document.createTextNode('HTML you might');
var theText3 = document.createTextNode('have');
var theText4 = document.createTextNode(' in your document');
theBoldBit.appendChild(theText2);
theBoldBit.appendChild(theBR);
theBoldBit.appendChild(theText3);
theNewParagraph.appendChild(theText1);
theNewParagraph.appendChild(theBoldBit);
theNewParagraph.appendChild(theText4);
document.getElementById('someElementId').appendChild(theNewParagraph);
Also, can anyone help me by explaining this?
What you have is a snippet of JavaScript code. I've added comments to the code to explain each section:
// Create 3 elements, a <p>, a <b> and a <br>
var theNewParagraph = document.createElement('p');
var theBoldBit = document.createElement('b');
var theBR = document.createElement('br');
// Set the title attribute of the <p> element we created
theNewParagraph.setAttribute('title','The test paragraph');
// Create 4 "text nodes", these appear as text when added to elements
var theText1 = document.createTextNode('This is a sample of some ');
var theText2 = document.createTextNode('HTML you might');
var theText3 = document.createTextNode('have');
var theText4 = document.createTextNode(' in your document');
/* Add the second text node, the <br> element and the 3rd text node to the
<b> element we created */
theBoldBit.appendChild(theText2);
theBoldBit.appendChild(theBR);
theBoldBit.appendChild(theText3);
/* Add the first text node, the <b> element and the 4th text node to the
<p> element we created. All nodes are now descendants of the <p> */
theNewParagraph.appendChild(theText1);
theNewParagraph.appendChild(theBoldBit);
theNewParagraph.appendChild(theText4);
/* Finally, add the <p> element to an element with an id attribute of
someElementId, so we can see all the content on our page */
document.getElementById('someElementId').appendChild(theNewParagraph);
The result is the following HTML as the content of someElementId:
<p title="The test paragraph">This is a sample of some <b>HTML you might<br>
have</b> in your document</p>
Others have explained how to add this script to your document using the <script> element.
Put the above in a <script type="text/javascript"> at the bottom of your page and make sure there's an <div id="someElementId"> in your document.
What it's doing is creating a new <p>, <b> and <br> tag. It then sets the title on the paragraph, adds some text to all tags and finally adds the whole mess to an element with id #someElementId.
You can see it in action here.
Here is a suitable test harness. Paste the following into a new .html file:
<html><head><script language="javascript"><!--// your javascript here:
function _onload()
{
var theNewParagraph = document.createElement('p');
var theBoldBit = document.createElement('b');
var theBR = document.createElement('br');
theNewParagraph.setAttribute('title','The test paragraph');
var theText1 = document.createTextNode('This is a sample of some ');
var theText2 = document.createTextNode('HTML you might');
var theText3 = document.createTextNode('have');
var theText4 = document.createTextNode(' in your document');
theBoldBit.appendChild(theText2);
theBoldBit.appendChild(theBR);
theBoldBit.appendChild(theText3);
theNewParagraph.appendChild(theText1);
theNewParagraph.appendChild(theBoldBit);
theNewParagraph.appendChild(theText4);
document.getElementById('someElementId').appendChild(theNewParagraph);
}
//--></script></head><body onload='_onload()' id='someElementId'></body></html>
How to run:
<head>
<script type="text/javascript">
function CreateTestParagraph () {
var theNewParagraph = document.createElement('p');
var theBoldBit = document.createElement('b');
var theBR = document.createElement('br');
theNewParagraph.setAttribute('title','The test paragraph');
var theText1 = document.createTextNode('This is a sample of some ');
var theText2 = document.createTextNode('HTML you might');
var theText3 = document.createTextNode('have');
var theText4 = document.createTextNode(' in your document');
theBoldBit.appendChild(theText2);
theBoldBit.appendChild(theBR);
theBoldBit.appendChild(theText3);
theNewParagraph.appendChild(theText1);
theNewParagraph.appendChild(theBoldBit);
theNewParagraph.appendChild(theText4);
document.getElementById('someElementId').appendChild(theNewParagraph);
}
</script>
</head>
<body onload="CreateTestParagraph ()">
<div id="someElementId"></div>
</body>
Your CreateTestParagraph method creates the following HTML content dynamically:
<p title="The test paragraph">This is a sample of some <b>HTML you might<br>have</b> in your document</p>
and put that contents into the someElementId element.
Related links:
createElement method,
createTextNode method,
appendChild method,
getElementById method,
onload event