I want to be able to create a JavaScript element where the script is included.
Example:
<script src='addDiv.js'></script>
The addDiv.js simply adds a customized div as below:
var element = document.createElement("div");
element.setAttribute("id", "myspecialdiv");
document.body.appendChild(element);
I want to add this div wherever this script is included instead of at the end of body. Is there a way to achieve this ?
Thanks
In most modern browsers you can use document.currentScript;
<script>
function replaceScript(el, text) {
let p = document.createElement('p')
p.innerText = text;
el.replaceWith(p);
}
</script>
<script>
replaceScript(document.currentScript, 'Test 1');
</script>
<script>
replaceScript(document.currentScript, 'Test 2');
</script>
Related
but insertbefore work
var a=document.querySelector("#div");
var y=document.createElement('p');
y.innerText='yazilarucun';
var c=document.querySelector(".p");
a.insertAfter(y,c);
<body>
<div id='div'>yazi
<p class='p'>p etiketi</p>
</div>
</body>
Your Problem Can be fixed pretty easily. You can fix this by adding the node before the node that is after the the node
function insertAfter(newNode, existingNode) {
existingNode.parentNode.insertBefore(newNode, existingNode.nextSibling);
}
//Create Element
var new_para = document.createElement('p');
new_para.innerText = 'yazilarucun';
//Add the element
var old_para = document.querySelector(".p");
insertAfter(new_para, old_para)
<body>
<div id='div'>yazi
<p class='p'>p etiketi</p>
</div>
</body>
The node.insertAfter() is not an inbuilt javascript method, instead we created a user-defined function.
<!DOCTYPE html>
<html>
<body>
<p id="point">Start</p>
<script>
var parentNode = document.getElementsByTagName("body")[0];
var refNode = document.getElementById("point");
function insertAfter(newNode, refNode){
refNode.parentNode.insertBefore(newNode, refNode.nextSibling);
}
var newNode = document.createElement("p");
var textnode = document.createTextNode("End");
newNode.appendChild(textnode);
insertAfter(newNode, refNode);
</script>
</body>
</html>
check : https://www.wikimass.com/js/node-insertafter
There is at least 3 ways to do it.
let targetNode = document.querySelector('#wrapper'),
placeNode = document.querySelector('#footer');
targetNode.after(placeNode);
targetNode.insertAdjacentElement('afterend', placeNode);
targetNode.parentNode.insertBefore(placeNode, targetNode.nextSibling);
The first of these 3, is the newest and simplest. Has been supported since Chrome 54+, Firefox 49+, Edge 17+. No IE support...
Last one is best support, oldest and most complicated one...
Middle one is somewhere in the middle... Is still too hard... Not intuitive enough...
I've been stuck on this for the longest time and it's driving me nuts. I've tried a dozen different methods and can't figure out how to get it to work. Any help would be appreciated!! Thanks
Here's my code:
<script>
function runScript() {
//get parent of script element
var element = document.currentScript.parentElement;
//my html string that needs to be inserted inside the original div
var item = "<div>test1</div><div>test2</div>";
//My current method. this method works but creates another wrapper div. I need a way to remove the wrapper div or a different method altogether without any wrapper divs.
var z = document.createElement('div');
z.innerHTML = item;
element.appendChild(z);
}
</script>
<div id="main-wrapper">
<script>
runScript();
</script>
</div>
<script>
function runScript() {
//get parent of script element
var element = document.currentScript.parentElement;
//my html string that needs to be inserted inside the original div
var item = "<div>test1</div><div>test2</div>";
element.innerHTML = item;
}
</script>
<div id="main-wrapper">
<script>
runScript();
</script>
</div>
As you've tagged with jQuery, you can create the element as follow:
$(item);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
function runScript() {
var item = "<div>test1</div><div>test2</div>";
$(document.currentScript.parentElement).append($(item));
}
</script>
<div id="main-wrapper">
<script>
runScript();
</script>
</div>
You can use the insertAdjacentHTML method.
<script>
function runScript() {
//get parent of script element
var element = document.currentScript.parentElement;
//my html string that needs to be inserted inside the original div
var item = "<div>test1</div><div>test2</div>";
element.insertAdjacentHTML('beforeend', item);
}
</script>
<div id="main-wrapper">
<script>
runScript();
</script>
</div>
Or use a template instead of a DIV.
<script>
function runScript() {
//get parent of script element
var element = document.currentScript.parentElement;
//my html string that needs to be inserted inside the original div
var item = "<div>test1</div><div>test2</div>";
var z = document.createElement('template');
z.innerHTML = item;
element.appendChild(z.content);
}
</script>
<div id="main-wrapper">
<script>
runScript();
</script>
</div>
When the call bellow is done the class creates a set of elements (a form) and then I want to append them right after the script that called it.
I have been looking at various similar questions but the best of them simply append it after the last script on the page.
It would work nicely in the head but not the body.
<script type="text/javascript">
new exampleClass();
</script>
You should have some type of unique identification to find and append elements after the script. You can use document.getElementById() if you have id, or document.getElementsByTagName("script") to get script elements and get the required script element and then use appendChild()
Ok, here is the horrible hack mentioned.
HTML
<div>Stuff</div>
<script type="text/javascript">
noop();
</script>
<div>More stuff</div>
<script type="text/javascript">
new ExampleClass();
</script>
<div>More stuff</div>
<script type="text/javascript">
noop();
</script>
<div>More stuff</div>
Javascript
function noop() {}
function appendAfter(node, newNode) {
if (node.nextSibling) {
node.parentNode.insertBefore(newNode, node.nextSibling);
} else {
node.parentNode.appendChild(newNode);
}
}
function ExampleClass() {
window.addEventListener("load", function () {
var scripts = document.getElementsByTagName("script"),
div = document.createElement("div"),
length = scripts.length,
i = 0,
script;
div.appendChild(document.createTextNode("Inserted"));
while (i < length) {
script = scripts[i];
if (script.firstChild && script.firstChild.nodeValue.indexOf("ExampleClass()") !== -1) {
appendAfter(script, div);
}
i += 1;
}
}, false);
}
On jsfiddle
Based on some of your comments and some other similar I have thought of doing something like this and it seems to work.
// Generate random string we can use as element id
var rs = Math.random().toString(36).substring(2);;
// Document write an empty div with the above string as id
document.write('<div id="' + rs + '"></div>');
// Get the element to use for append
var ip = document.getElementById(rs);
Please feel free to comment if you think it may have a fatal flaw.
I am trying to change the contents of a div without using jQuery. I want to select the div by id or class.
Ive managed to get append to work:
function appendHtml(targetC, htmldata) {
var theDiv = document.getElementById(targetC);
var newNode = document.createElement('div');
newNode.innerHTML = htmldata;
theDiv.appendChild(newNode)
}
But cant figure out how to change text of one..
Any ideas?
see this fiddle for a basic sample
<html>
<head>
<script>
function bold(targetC) {
var theDiv = document.getElementById(targetC);
theDiv.innerHTML = '<b>' + theDiv.innerHTML + '</b>';
}
</script>
</head>
<body onload='bold("message")'>
<div>Hello, World!</div>
<div id="message">What a nice day!</div>
</body>
</html>
Edited:
<div id="foo">old text</div>
The JS code:
function appendHtml(targetC, htmldata) {
var theDiv = document.getElementById(targetC);
theDiv.innerHTML = htmldata;
}
appendHtml('foo', 'new text');
Here is a fiddle: http://jsfiddle.net/7QjcB/
simply change the html of a div by using innerHTML
var anyDiv = document.getElementById(targetID);
html = "content";
anydiv.innerHTML(html);
as a variation of your provided function:
function changeHtml(targetC, htmldata) {
var theDiv = document.getElementById(targetC);
theDIV.innerHTML = htmldata;
}
Here is a fiddle that might answer your question. All I changed was getting the element before and then passing it in.
function appendHtml(targetC, htmldata) {
var newNode = document.createElement('div');
newNode.innerHTML = htmldata;
targetC.appendChild(newNode);
}
var getDiv = document.getElementById("testing");
On nydailynews.com when you copy and paste any text from the site, a snippet of text is appended.
Read more: http://www.nydailynews.com/#ixzz0aN123abc
How do they achieve this?
I have searched all of the external JavaScript files (jquery) and can't seem to find anything that corresponds. Is this something that could be done in simple css?
If you use EventBug in Firefox, you'll see that a copy event fires. The JS on the page is listening for this event and changing the clipboard contents. There are so many files loaded by that page it's hard to find the source code, though.
Use this code to add extra text to the copied content
Source : http://bavotasan.com/2010/add-a-copyright-notice-to-copied-text/
<script type="text/javascript">
function addLink() {
var body_element = document.getElementsByTagName('body')[0];
var selection;
selection = window.getSelection();
var pagelink = "<br /><br /> Read more at: <a href='"+document.location.href+"'>"+document.location.href+"</a><br />Copyright © c.bavota"; // change this if you want
var copytext = selection + pagelink;
var newdiv = document.createElement('div');
newdiv.style.position='absolute';
newdiv.style.left='-99999px';
body_element.appendChild(newdiv);
newdiv.innerHTML = copytext;
selection.selectAllChildren(newdiv);
window.setTimeout(function() {
body_element.removeChild(newdiv);
},0);
}
document.oncopy = addLink;
</script>