I want to move this code from my html-file to a js-file, is there any smooth way to do this without having to put the HTML-code as a string?
<script type="text/template" id="template_test">
<h4>Test</h4>
<p>blablabla</p>
</script>
Thanks!
You can use the createElement function to create HTML elements however if you intend to move alot of code you should consider using a templeting engine.
// Create the <h4> element
var heading = document.createElement("h4");
// add the text
heading.textContent = "TEST";
// Create the text node <p>
var p = document.createTextNode("blablabla");
//get the element to which you want to append the h4 and p
var container = document.getElementById("myID");
// Append h4 and p
container.appendChild(heading);
container.appendChild(p);
Related
I have a bit of JS to add an email hyperlink to a page, after a DIV with an ID value of section_form_id:
// build email
var elmNewContentCustomer = document.createElement('a');
var elmFoo = document.getElementById('section_form_id');
elmNewContentCustomer.href = 'mailto:me#example.com?subject=Something';
elmNewContentCustomer.setAttribute("style", "color:blue;");
elmNewContentCustomer.setAttribute("id", "email_customer_id");
elmNewContentCustomer.appendChild(document.createTextNode('Email Customer'));
elmFoo.parentNode.insertBefore(elmNewContentCustomer, elmFoo.nextSibling);
This works fine. However, I'd like to put the hyperlink inside a DIV so I set the style attributes of the DIV.
I tried using this method, which was to create a DIV, and insert it before the email block using appendChild but it doesn't work:
var elmNewEmailDev = document.createElement('div');
var elmFoo2 = document.getElementById('email_customer_id');
elmNewEmailDev.setAttribute("style", "background:yellow;");
elmNewEmailDev.appendChild(elmFoo.parentNode.insertBefore(elmNewContentCustomer, elmFoo.nextSibling));
elmFoo2.parentNode.insertBefore(elmNewEmailDev, elmFoo.elmFoo2);
How can I wrap a DIV around the hyperlink so I can then use setAttribute to be able to control the style of that DIV?
Follow this method your get result as you want.
var myEmailLink = "<a href='mailto:a#b.com'>a#b.com</a>";
var myDiv = document.getElementById("section_form_id");
myDiv.insertAdjacentHTML('afterEnd', myEmailLink )
<div id="section_form_id">
My Div Here
</div>
I want to replace an old element with a wrapped new one.
I begin like this:
<div>Some text
<span id="old"></span>
</div>
And I want this:
<div>Some text
<span>
<a></a>
</span>
</div>
I manage to replace the old element with the new one like this:
var elementA = document.querySelector('#old')
var elementB = document.createElement("a")
elementA.before(elementB)
elementA.remove()
Result:
<div>Some text
<a></a>
</div>
But I cannot manage to wrap the new element in the meantime. I tried to override Element.outerHTML, and jQuery wrap(), without success. Any idea please?
EDIT: I noticed I oversimplified my use case... here is the more precise code:
var elementA = document.querySelector('#old')
var elementB = document.createElement("a")
// Here I do manipulations on elementB: add classes, set Id, set attributes, set innerHTML, etc.
elementA.before(elementB)
elementA.remove()
So elementB is really an "element" (or node?), not just HTML. Maybe I can turn this element into raw HTML and insert it in the wrapper with innerHTML as per suggestions below?
If you want to look at the actual code here it is.
var elementA = document.querySelector('#old')
var elementB = document.createElement("span")
elementB.innerHTML = '<span></span>';
elementA.before(elementB)
elementA.remove()
<div>Some text
<span id="old"></span>
</div>
You could try this:
You don't need to change the HTML for this...
var elementA = document.querySelector('#old');
var elementB = document.createElement("span");
elementB.innerHTML = '<span></span>';
elementA.before(elementB);
elementA.remove()
If I insert a comment node into a document fragment, can I convert it to HTML later? Example:
var fragment = document.createDocumentFragment();
var comment = document.createComment('<div>Testing</div>');
fragment.appendChild(comment);
// Convert comment into actual HTML?
What this would look like inside of a fragment:
<!--<div>Testing</div>-->
And how it should be when done (actual DOM):
<div>Testing</div>
Background:
There are many limitations for inserting HTML into a fragment. Fragments don't support innerHTML or insertAdjacentHTML etc. There are other methods for getting HTML into fragments, but they drop certain elements and leave only the inner text. For example, creating a fragment with the createRange API drops those types of nodes and I will be left with a fragment with just the text node "Data"
var fragment = document.createRange().createContextualFragment('<td>Data</td>');
The hope is that if I can convert a comment into actual DOM, that it will work as expected.
For the entire body you can use that snippet:
var body = document.getElementsByTagName('body')[0],
bodyHtml = body.innerHTML;
while (bodyHtml.indexOf("<!--") !== -1) { // will replace all the comments with empty string
bodyHtml = bodyHtml.replace("<!--", "").replace("-->", "");
}
body.innerHTML = bodyHtml;
Hello
<h1>hi</h1>
<!--<div>Testing</div>-->
<!--<div>Testing</div>-->
It sounds like your underlying problem is that you need to stuff HTML text into a DocumentFragment, so here is a helper function to do so for you.
var container = document.createElement('div')
function createFragmentWithHTML (html, doc) {
var result = (doc || document).createDocumentFragment()
container.innerHTML = html
while (container.firstChild) result.appendChild(container.firstChild)
return result
}
var fragment = createFragmentWithHTML('<div>Testing</div><p><strong>More text</strong></p>')
// do whatever you want with `fragment`
document.body.appendChild(fragment)
Something like this would do the trick
var element = document.getElementById("whatever"); // get the parent element
var comment = element.innerHTML; // get the thml
var html = comment.replace("<!--", "").replace("-->", ""); // remove the comment
element.innerHTML = html;
Text content of an HTML comment can be accessed via the nodeValue property of the Node interface or the data property of the CharacterData interface that the HTML Comment interface inherits from:
<!--<div>Example</div>-->
var code = comment.data; /* Now contains `<div>Example</div>` text */
var code = comment.nodeValue; // Same result.
Fwiw, I have a blog post about using HTML comment as data container.
You can get your comments with element.childNodes method, then use textContent method to get the content of comment, then change it into HTML Element with innerHTML method, then remove the comment node and replace it with Element Node.
parseComments('container');
function parseComments(getContainerId){
var container = document.getElementById(getContainerId);
var nodes = container.childNodes;
for(var i=0;i<nodes.length;i++){
if(nodes[i].nodeType===8){
var virtualCont = document.createElement('DIV');
var getContent = nodes[i].textContent;
virtualCont.innerHTML = getContent;
container.removeChild(nodes[i]);
if(nodes[i+1]){
container.insertBefore(virtualCont.children[0],nodes[i+1]);
} else {
container.appendChild(virtualCont.children[0]);
}
}
}
}
<div id="container">
<h1>some header A</h1>
<!--<p>some hidden content A</p>-->
<p>some content</p>
<!--<p>some hidden content B</p>-->
<p>another content</p>
<!--<h1>some hidden header B</h1>-->
<!--<p>another hidden content C</p>-->
</div>
I'm a complete beginner in JavaScript and I am trying to create a script which is fired when a "file input" element of the page gets a file loaded. The script should basically create a p element, insert in it an img, a innerText and a span, hence append all this into a form. Everything works fine with the script below, except for the img:
function visualUploadFile() {
var obj = document.getElementById("hidden_file").files[0].name;
//create p object to append to the form
var pobj = document.createElement("p");
pobj.className = "form_line_file";
//nest icon inside the object
var imgico = document.createElement("img");
imgico.src = "load-ico.png";
//append img to the p - THE OBJECT IS NOT APPENDED
pobj.appendChild(imgico);
//nest file name as inner Text to the p
pobj.innerText = obj;
//create span object to write "rimuovi"
var spanobj = document.createElement("span");
spanobj.className = "rimuovi_file";
spanobj.innerHTML = "rimuovi";
//append span to the p
pobj.appendChild(spanobj);
//get form and append p child
var bigForm = document.getElementById("offerta_form");
bigForm.appendChild(pobj);
}
Here is the HTML after the script has been executed, as you can see only the img is missing:
<p class="form_line_file"> <!--p object correctly appended to the form-->
Immagine.png <!--inner Text properly appended-->
<span class="rimuovi_file"> <!--span object correctly appended-->
rimuovi
</span>
</p>
Probably is a stupid mistake, but I'm not being able to sort it out. Could anyone please tell me what I'm doing wrong not to be able to get the img appended as for the span?
The way you are adding file name label is incorrect. Setting innerText overwrites image. Instead of
pobj.innerText = obj;
try this:
pobj.appendChild(document.createTextNode(obj));
i am working on this example of appendChild() method.but the difference is here i am trying to add more text to a div dynamically.that was all right.but the hard part is the text i want to add will be red in color.how can i do that?
i tried
text.setAttributes('color',"red");
But it didn't work.so,how this task can be done??please help,thanks!!!!
the full code is given below............
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function create_text(){
var mydiv = document.getElementById("mydiv");
var text = document.createTextNode(" New text to add.");
mydiv.appendChild(text);
}
</script>
</head>
<body>
<button onclick="create_text();">Create Text Node</button>
<div id="mydiv">Welcome, here is some text.</div>
</body>
</html>
You would normally have to use CSS properties, however, text nodes cannot have CSS properties applied to them. You therefore need another container element:
You can choose any container element you wish, e.g. div, span, etc. It just needs to be capable of containing a text node. Having an element then allows us to access the styles property and set various styles (the color attribute in your case).
→ jsFiddle
function create_text(){
var mydiv = document.getElementById("mydiv");
var container = document.createElement("span");
var text = document.createTextNode(" New text to add.");
container.appendChild(text);
container.style.color = "red";
mydiv.appendChild(container);
}
Further note:
the order of the color assignments and calls of appendChild is arbitrary. The following would also be possible:
function create_text(){
var mydiv = document.getElementById("mydiv");
var container = document.createElement("span");
var text = document.createTextNode(" New text to add.");
container.appendChild(text);
mydiv.appendChild(container);
container.style.color = "red";
}
mydiv.style.color = 'red';
or just in css
#mydiv { color: red; }
if you have other elements inside the div that you don't want to be red, you'd need to wrap the new text in a span or div or another element before appending.
with jquery this would be super easy:
$('#mydiv').append('<span style="color:red">this is new text</span>');
If that's everything in your div, you could try
document.getElementById("mydiv").style.color="#ff0000";