Appendchild javascript script tag

Node: appendChild() method

The appendChild() method of the Node interface adds a node to the end of the list of children of a specified parent node.

Note: If the given child is a reference to an existing node in the document, appendChild() moves it from its current position to the new position.

If the given child is a DocumentFragment , the entire contents of the DocumentFragment are moved into the child list of the specified parent node.

appendChild() returns the newly appended node, or if the child is a DocumentFragment , the emptied fragment.

Note: Unlike this method, the Element.append() method supports multiple arguments and appending strings. You can prefer using it if your node is an element.

Syntax

Parameters

The node to append to the given parent node (commonly an element).

Return value

A Node that is the appended child ( aChild ), except when aChild is a DocumentFragment , in which case the empty DocumentFragment is returned.

Exceptions

Thrown when the constraints of the DOM tree are violated, that is if one of the following cases occurs:

  • If the parent of aChild is not a Document , DocumentFragment , or an Element .
  • If the insertion of aChild would lead to a cycle, that is if aChild is an ancestor of the node.
  • If aChild is not a DocumentFragment , a DocumentType , an Element , or a CharacterData .
  • If the current node is a Text , and its parent is a Document .
  • If the current node is a DocumentType and its parent is not a Document , as a doctype should always be a direct descendant of a document.
  • If the parent of the node is a Document and aChild is a DocumentFragment with more than one Element child, or that has a Text child.
  • If the insertion of aChild would lead to Document with more than one Element as child.
Читайте также:  If выражение true python

Description

If the given child is a reference to an existing node in the document, appendChild() moves it from its current position to the new position — there is no requirement to remove the node from its parent node before appending it to some other node. This means that a node can’t be in two points of the document simultaneously. The Node.cloneNode() method can be used to make a copy of the node before appending it under the new parent. Copies made with cloneNode are not automatically kept in sync.

appendChild() returns the newly appended node, instead of the parent node. This means you can append the new node as soon as it’s created without losing reference to it:

const paragraph = document.body.appendChild(document.createElement("p")); // You can append more elements to the paragraph later 

On the other hand, you cannot use appendChild() in a fluent API fashion (like JQuery).

// This doesn't append three paragraphs: // the three elements will be nested instead of siblings document.body .appendChild(document.createElement("p")) .appendChild(document.createElement("p")) .appendChild(document.createElement("p")); 

Example

Append a paragraph to the body

// Create a new paragraph element, and append it to the end of the document body const p = document.createElement("p"); document.body.appendChild(p); 

Creating a nested DOM structure

In this example, we attempt to create a nested DOM structure using as few temporary variables as possible.

const fragment = document.createDocumentFragment(); const li = fragment .appendChild(document.createElement("section")) .appendChild(document.createElement("ul")) .appendChild(document.createElement("li")); li.textContent = "hello world"; document.body.appendChild(fragment); 

It generates the following DOM tree:

section> ul> li>hello worldli> ul> section> 

Specifications

Browser compatibility

BCD tables only load in the browser

See also

Found a content problem with this page?

This page was last modified on Apr 13, 2023 by MDN contributors.

Your blueprint for a better internet.

MDN

Support

Our communities

Developers

Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.

Источник

Appendchild javascript script tag

Last updated: Nov 22, 2022
Reading time · 2 min

banner

# Create a Script element using JavaScript

To create a script element in JavaScript:

  1. Use the document.createElement() method to create the script element.
  2. Set the src attribute on the element to a local or remote JavaScript file.
  3. Add the element to the page using the appendChild() method.

Here is the HTML for the examples.

Copied!
DOCTYPE html> html lang="en"> head> title>bobbyhadz.comtitle> meta charset="UTF-8" /> head> body> div id="box">div> script src="index.js"> script> body> html>

And here is the related JavaScript code.

Copied!
const script = document.createElement('script'); // 👇️ local file // script.setAttribute('src', 'another-file.js'); // 👇️ remote file script.setAttribute( 'src', 'https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js', ); script.setAttribute('async', ''); // 👇️ optionally set script to be treated as JS module // script.setAttribute('type', 'module'); script.onload = function handleScriptLoaded() console.log('script has loaded'); document.getElementById('box').textContent = 'Script loaded successfully'; >; script.onerror = function handleScriptError() console.log('error loading script'); >; document.head.appendChild(script);
Copied!
const script = document.createElement('script');

Источник

Can’t append element

define «not working»- though I suspect the problem is that scripts aren’t really part of the dom tree.

My bet is that the script node is being added to the DOM, but the browser just isn’t executing the script.

@Joel — «not working» = it does not have any effect, i.e. the code within the script is not executed @Outlaw Programmer — the node is not added to the DOM @Jimmy Yes, I have tested it and it’s not working

19 Answers 19

The Good News is:

Just add something inside the script tag such as alert(‘voila!’); . The right question you might want to ask perhaps, «Why didn’t I see it in the DOM?».

Karl Swedberg has made a nice explanation to visitor’s comment in jQuery API site. I don’t want to repeat all his words, you can read directly there here (I found it hard to navigate through the comments there).

All of jQuery’s insertion methods use a domManip function internally to clean/process elements before and after they are inserted into the DOM. One of the things the domManip function does is pull out any script elements about to be inserted and run them through an «evalScript routine» rather than inject them with the rest of the DOM fragment. It inserts the scripts separately, evaluates them, and then removes them from the DOM.

I believe that one of the reasons jQuery does this is to avoid «Permission Denied» errors that can occur in Internet Explorer when inserting scripts under certain circumstances. It also avoids repeatedly inserting/evaluating the same script (which could potentially cause problems) if it is within a containing element that you are inserting and then moving around the DOM.

The next thing is, I’ll summarize what’s the bad news by using .append() function to add a script.

And The Bad News is..

I’m not joking, even if you add debugger; keyword between the line you want to set as breakpoint, you’ll be end up getting only the call stack of the object without seeing the breakpoint on the source code, (not to mention that this keyword only works in webkit browser, all other major browsers seems to omit this keyword).

If you fully understand what your code does, than this will be a minor drawback. But if you don’t, you will end up adding a debugger; keyword all over the place just to find out what’s wrong with your (or my) code. Anyway, there’s an alternative, don’t forget that javascript can natively manipulate HTML DOM.

Use javascript (not jQuery) to manipulate HTML DOM

If you don’t want to lose debugging capability, than you can use javascript native HTML DOM manipulation. Consider this example:

var script = document.createElement("script"); script.type = "text/javascript"; script.src = "path/to/your/javascript.js"; // use this for linked script script.text = "alert('voila!');" // use this for inline script document.body.appendChild(script); 

There it is, just like the old days isn’t it. And don’t forget to clean things up whether in the DOM or in the memory for all object that’s referenced and not needed anymore to prevent memory leaks. You can consider this code to clean things up:

document.body.removechild(document.body.lastChild); delete UnusedReferencedObjects; // replace UnusedReferencedObject with any object you created in the script you load. 

The drawback from this workaround is that you may accidentally add a duplicate script, and that’s bad. From here you can slightly mimic .append() function by adding an object verification before adding, and removing the script from the DOM right after it was added. Consider this example:

function AddScript(url, object) < if (object != null)< // add script var script = document.createElement("script"); script.type = "text/javascript"; script.src = "path/to/your/javascript.js"; document.body.appendChild(script); // remove from the dom document.body.removeChild(document.body.lastChild); return true; >else < return false; >; >; function DeleteObject(UnusedReferencedObjects)

This way, you can add script with debugging capability while safe from script duplicity. This is just a prototype, you can expand for whatever you want it to be. I have been using this approach and quite satisfied with this. Sure enough I will never use jQuery .append() to add a script.

Источник

Appendchild javascript script tag

Last updated: Nov 22, 2022
Reading time · 2 min

banner

# Create a Script element using JavaScript

To create a script element in JavaScript:

  1. Use the document.createElement() method to create the script element.
  2. Set the src attribute on the element to a local or remote JavaScript file.
  3. Add the element to the page using the appendChild() method.

Here is the HTML for the examples.

Copied!
DOCTYPE html> html lang="en"> head> title>bobbyhadz.comtitle> meta charset="UTF-8" /> head> body> div id="box">div> script src="index.js"> script> body> html>

And here is the related JavaScript code.

Copied!
const script = document.createElement('script'); // 👇️ local file // script.setAttribute('src', 'another-file.js'); // 👇️ remote file script.setAttribute( 'src', 'https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js', ); script.setAttribute('async', ''); // 👇️ optionally set script to be treated as JS module // script.setAttribute('type', 'module'); script.onload = function handleScriptLoaded() console.log('script has loaded'); document.getElementById('box').textContent = 'Script loaded successfully'; >; script.onerror = function handleScriptError() console.log('error loading script'); >; document.head.appendChild(script);
Copied!
const script = document.createElement('script');

Источник

Оцените статью