I found the explaination about the API here, which tells me the second parameter is a string.
It's perform normal in firefox. However, in chrome, it shows the errors below:
I just curious about what makes this? Is it because the api is still stay Working Draft status and different browsers do the different implementation?
The following is my code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div id="div">
<ul>
<li>xxx</li>
<li>xxx</li>
<li>xxx</li>
<li>xxx</li>
<li>xxx</li>
</ul>
</div>
<script>
//normal
// var pTag=document.createElement("p");
// div.insertAdjacentElement("beforeend",pTag);
//throw error:
// Uncaught TypeError: Failed to execute 'insertAdjacentElement' on 'Element': parameter 2 is not of type 'Element'.
var txt = "<p>testtest</p>";
div.insertAdjacentElement("beforeend",txt);
</script>
</body>
</html>
The insertAdjacentHTML() method of the Element interface parses the specified text as HTML or XML and inserts the resulting nodes into the DOM tree at a specified position.
When one is clicked, it becomes selected and you can then press the Insert before and Insert after buttons to insert new divs before or after the selected element using insertAdjacentElement() .
Definition and Usage The insertAdjacentHTML() method inserts HTML code into a specified position. Legal positions: Value.
Just Change div.insertAdjacentElement
to div.insertAdjacentHTML
:
<!-- <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Coding revoltion</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<div class="parent">
<ul class="ul"></ul>
</div>
<script src="dom.js"></script>
</body>
</html>
-->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div id="div">
<ul>
<li>xxx</li>
<li>xxx</li>
<li>xxx</li>
<li>xxx</li>
<li>xxx</li>
</ul>
</div>
<script>
//normal
// var pTag=document.createElement("p");
// div.insertAdjacentElement("beforeend",pTag);
//throw error:
// Uncaught TypeError: Failed to execute 'insertAdjacentElement' on 'Element': parameter 2 is not of type 'Element'.
var txt = "<p>testtest</p>";
div.insertAdjacentHTML("beforeend",txt);
</script>
</body>
</html>
The parameters are incorrect. The second parameter should be html element, in your case it's a string.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With