Is it possible to append a second child into the first appendchild created in a single line of code?
Something like this:
document.body.appendChild(document.createElement('p').appendChild(document.createTextNode('Some Text)));
This works fine, but i want to know why it doesn't work the same way in a single line of code.
let p = document.createElement('p');
p.appendChild(document.createTextNode('Some Text'));
document.body.appendChild(p);
document.body.appendChild(document.createElement('p').appendChild(document.createTextNode('Some Text')));
evaluates to
const p = document.createElement('p');
const node = document.createTextNode('Some Text');
document.body.appendChild(node);
because document.createTextNode is the last thing called, which returns the DOM node of the text
So when you run this, 'Some Text' is added to the DOM, but it's not actually inside the <p> tag
You should append the paragraph first, so this code
document.body.appendChild(document.createElement('p').appendChild(document.createTextNode('Some Text)));
should be like this:
document.body.appendChild(document.createElement('p')).appendChild(document.createTextNode('Some Text')));
Related
I have a content that contains a string of elements along with images. ex:
var str= <p><img src=\"v\">fwefwefw</img></p><p><br></p><p><br></p>
the text that is within the < and > is a dirty tag and I would like to remove it along with the content that is within it. the tag is generated dynamically and hence could be any tag i.e <div>, <a>, <h1> etc....
the expected output : <p></p><p><br></p><p><br></p>
however with this code, im only able to remove the tags and not the content inside it.
str.replaceAll(/<.*?>/g, "");
it renders like this which is not what im looking for:
<p>fwefwefw</p><p><br></p><p><br></p><p><br></p>
how can I possibly remove the & tags along with the content so that I get rid of dirty tags and text inside it?
fiddle: https://jsfiddle.net/3rozjn8m/
thanks
A safe way is to use a DOM parser, visiting each text node, where then each text can be cleaned separately. This way you are certain the DOM structure is not altered; only the texts:
let str= "<p><img src=\"v\">fwefwefw</img></p><p><br></p><p><br></p>";
let doc = new DOMParser().parseFromString(str, "text/html");
let walk = doc.createTreeWalker(doc.body, 4, null, false);
let node = walk.nextNode();
while (node) {
node.nodeValue = node.nodeValue.replace(/<.*>/gs, "");
node = walk.nextNode();
}
let clean = doc.body.innerHTML;
console.log(clean);
This will also work when you have more than one <p> element that has such content.
Remove the question mark.
var str= "<p><img src=\"v\">fwefwefw</img></p><p><br></p><p><br></p>";
console.log(str.replaceAll(/<.*>/g, ""));
Example:
var buttonHTML = "<button>MyButton</button>";
document.getElementById("myDiv").append(buttonHTML);
In this case, the function ends up appending the text into the div.
However, if I do the same with JQ:
$("#myDiv").append(buttonHTML);
In this case it will actually append the button.
Now, for various reasons, I have to use plain JS (not JQ).
Anyone have any ideas?
I am not sure how it worked with you and appended the element as text here, because there is no .append function in pure JS
But I agree with what #Sam Judge said in his answer,and also want to mention that you can do it using javascript without creating nodes one by one using javascript function Element.insertAdjacentHTML()
insertAdjacentHTML() parses the specified text as HTML or XML and
inserts the resulting nodes into the DOM tree at a specified position.
It does not reparse the element it is being used on and thus it does
not corrupt the existing elements inside the element. This avoiding
the extra step of serialization make it much faster than direct
innerHTML manipulation.
And there is another option to do the same using the .innerHTML but for sure you will need to save what's already inside to do the append effect.
This is because your var buttonHTML is just a string of text, if you append it as a child, it will create a DOM textNode, rather than an elementNode. What you want to do instead is something along the lines of the following :
var buttonHTML = document.createElement("button");
var buttonText = document.createTextNode("MyButton");
buttonHTML.appendChild(buttonText);
document.getElementById("myDiv").appendChild(buttonHTML)
you can try this code
function myFunction() {
var myButton= document.createElement("button");
myButton.style.width = "100px";
myButton.style.height = "30px";
myButton.style.background = "grey";
myButton.style.color = "white";
myButton.innerHTML = "MyButton";
document.getElementById("demo1").appendChild(myButton);
}
<button type="button" onclick="myFunction()">create another button</button>
<p id="demo1"></p>
Noob here. I searched on the internet a bit to find an answer to a question and I can't seem to find any (and that brings my hope down). So here I am.
I was wondering if there is a way to create an HTML element with javascript, BUT inside the newly created HTML element to create also another HTML element with javascript. I guess you can call it elementception //wink
To be more specific, I would like to create a paragraph with text, but I would like to include links in that text (or possibly buttons?).
var para = document.createElement("P");
var t = document.createTextNode("This is a paragraph. Can I do this: <a href='blabla'>like so?</a>");
para.appendChild(t);
document.body.appendChild(para);
I tried writing HTML tags inside the strings of the TextNode, but even I can see that was stupid of me. Is there a noobish(simple) way to achieve this, or any way at all? If I'm asking the impossible, please be harsh and blunt about it, so that I never ask questions again.
Thanks.
The simplest way to do this would be:
para.innerHTML = 'This is a paragraph. Here is a link: like so?';
I would use the DOM API approach instead of using innerHTML for readability, maintainability and security reasons. Sure innerHTML has been around for a long time, but just because it is easy doesn't mean you should use it for everything.
As well, if you're going to be learning JavaScript you should get acquainted with the DOM API sooner than later. It will save you a lot of headaches down the road if you get the hang of the API now.
// Create the parent and cache it in a variable.
var para = document.createElement( "p" );
// Create a text node and append it to the child.
// We don't need to cache this one because we aren't accessing it again.
para.appendChild( document.createTextNode( "This is a paragraph. Can I do this: " ) );
// Create our link element and cache it in a variable.
var link = document.createElement( "a" );
// Set the link's href attribute.
link.setAttribute( 'href', 'blabla' );
// Create a text node and append it to the link
// We don't need to cache the text node.
link.appendChild( document.createTextNode( 'like so?' ));
// Append the link to the parent.
para.appendChild( link );
// Append the parent to the body.
document.body.appendChild( para );
DOM API methods used:
Document.createElement()
Document.createTextNode()
Node.appendChild()
Element.setAttribute()
Further reading:
Document Object Model (DOM)
Element.innerHTML Security Considerations
Advantages of createElement over innerHTML?
Simply use innerHTML attribute to put HTML inside your element instead of createTexteNode, here's what you need:
var para = document.createElement("P");
para.innerHTML = "This is a paragraph. Can I do this: <a \"blabla\">like so?</a>";
document.body.appendChild(para);
Because as its name says, document.createTextNode() will only create a text and can't create HTML elements.
var para = document.createElement("P");
para.innerHTML = "This is a paragraph. Can I do this: like so?";
document.body.appendChild(para);
I need to change the text inside HTML element using javascript, but I have no idea about how to do it. ¿Any help?
I've got it defined like:
<h2 id="something">Text I want to change.</h2>
Im trying to do it with:
document.getElementById("something").value = "new text";
But it doesn't work.
Thanks
You can use innerHTML:
document.getElementById("something").innerHTML = "new text";
If the element only contains text, textContent works better and faster than innerHTML
document.getElementById("something").textContent = 'new text';
Good luck
:)
Though the following code would be the fastest alternative to slow .innerHTML:
var element = document.getElementById('something');
// removing everything inside the node
while (element.firstChild) {
element.removeChild(element.firstChild);
}
// appending new text node
element.appendChild(document.createTextNode('new text'));
And here is the benchmark:
JSPerf: http://jsperf.com/replace-text-in-node
I’m using AJAX to append data to a <div> element, where I fill the <div> from JavaScript. How can I append new data to the <div> without losing the previous data found in it?
Try this:
var div = document.getElementById('divID');
div.innerHTML += 'Extra stuff';
Using appendChild:
var theDiv = document.getElementById("<ID_OF_THE_DIV>");
var content = document.createTextNode("<YOUR_CONTENT>");
theDiv.appendChild(content);
Using innerHTML:
This approach will remove all the listeners to the existing elements as mentioned by #BiAiB. So use caution if you are planning to use this version.
var theDiv = document.getElementById("<ID_OF_THE_DIV>");
theDiv.innerHTML += "<YOUR_CONTENT>";
Beware of innerHTML, you sort of lose something when you use it:
theDiv.innerHTML += 'content';
Is equivalent to:
theDiv.innerHTML = theDiv.innerHTML + 'content';
Which will destroy all nodes inside your div and recreate new ones. All references and listeners to elements inside it will be lost.
If you need to keep them (when you have attached a click handler, for example), you have to append the new contents with the DOM functions(appendChild,insertAfter,insertBefore):
var newNode = document.createElement('div');
newNode.innerHTML = data;
theDiv.appendChild(newNode);
If you want to do it fast and don't want to lose references and listeners use: .insertAdjacentHTML();
"It does not reparse the element it is being used on and thus it does not corrupt the existing elements inside the element. This, and avoiding the extra step of serialization make it much faster than direct innerHTML manipulation."
Supported on all mainline browsers (IE6+, FF8+,All Others and Mobile): http://caniuse.com/#feat=insertadjacenthtml
Example from https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML
// <div id="one">one</div>
var d1 = document.getElementById('one');
d1.insertAdjacentHTML('afterend', '<div id="two">two</div>');
// At this point, the new structure is:
// <div id="one">one</div><div id="two">two</div>
If you are using jQuery you can use $('#mydiv').append('html content') and it will keep the existing content.
http://api.jquery.com/append/
IE9+ (Vista+) solution, without creating new text nodes:
var div = document.getElementById("divID");
div.textContent += data + " ";
However, this didn't quite do the trick for me since I needed a new line after each message, so my DIV turned into a styled UL with this code:
var li = document.createElement("li");
var text = document.createTextNode(data);
li.appendChild(text);
ul.appendChild(li);
From https://developer.mozilla.org/en-US/docs/Web/API/Node/textContent :
Differences from innerHTML
innerHTML returns the HTML as its name indicates. Quite often, in order to retrieve or write text within an element, people use innerHTML. textContent should be used instead. Because the text is not parsed as HTML, it's likely to have better performance. Moreover, this avoids an XSS attack vector.
Even this will work:
var div = document.getElementById('divID');
div.innerHTML += 'Text to append';
An option that I think is better than any of the ones mentioned so far is Element.insertAdjacentText().
// Example listener on a child element
// Included in this snippet to show that the listener does not get corrupted
document.querySelector('button').addEventListener('click', () => {
console.log('click');
});
// to actually insert the text:
document.querySelector('div').insertAdjacentText('beforeend', 'more text');
<div>
<button>click</button>
</div>
Advantages to this approach include:
Does not modify the existing nodes in the DOM; does not corrupt event listeners
Inserts text, not HTML (Best to only use .insertAdjacentHTML when deliberately inserting HTML - using it unnecessarily is less semantically appropriate and can increase the risk of XSS)
Flexible; the first argument to .insertAdjacentText may be beforebegin, beforeend, afterbegin, afterend, depending on where you'd like the text to be inserted
you can use jQuery. which make it very simple.
just download the jQuery file add jQuery into your HTML
or you can user online link:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
and try this:
$("#divID").append(data);
The following method is less general than others however it's great when you are sure that your last child node of the div is already a text node. In this way you won't create a new text node using appendData MDN Reference AppendData
let mydiv = document.getElementById("divId");
let lastChild = mydiv.lastChild;
if(lastChild && lastChild.nodeType === Node.TEXT_NODE ) //test if there is at least a node and the last is a text node
lastChild.appendData("YOUR TEXT CONTENT");
java script
document.getElementById("divID").html("this text will be added to div");
jquery
$("#divID").html("this text will be added to div");
Use .html() without any arguments to see that you have entered.
You can use the browser console to quickly test these functions before using them in your code.
Why not just use setAttribute ?
thisDiv.setAttribute('attrName','data you wish to append');
Then you can get this data by :
thisDiv.attrName;