Element.insertAdjacentHTML() API throws error in chrome 55.0.2883.87 - javascript

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>

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.

Your txt variable must be an element. You can try this :
var txt = document.createElement("p")
txt.innerHTML = "testtest";
div.insertAdjacentElement("beforeend",txt);

There are two methods to insert new block of elements :
insertAdjacentElement(position, element)
The second parameter should be an element and not html text.
E.g.
var newDiv = document.createElement('div');
newDiv.style.backgroundColor = 'white';
parentElement.insertAdjacentElement('beforeend',newDiv);
insertAdjacentHTML(position, text)
text is valid html text or xml.
e.g.
var newDiv = `<div>This is a new div</div>
<p> Hello !! </p>`;
parentDiv.addAdjacentHTML('beforeend',newDiv);

first create a new html element programatically var htmlObject = document.createElement('div'); then assign your string to newly created object htmlObject.innerHTML=htmlString;.
var htmlString = `<div class="item clearfix" id="income-${obj.id}">
<div class="item__description">${obj.descripiton}</div>
<div class="right clearfix">
<div class="item__value">${obj.value}</div>
<div class="item__delete">
<button class="item__delete--btn"><i class="ion-ios-close-outline"></i></button>
</div>
</div>
</div>`
var htmlObject = document.createElement('div');
htmlObject.innerHTML=htmlString;
document.querySelector(".income__list").insertAdjacentElement('beforeend', htmlObject);

You can use either Obj.innerHTML or Obj.insertAdjacentHTML() if you want to continue with String HTML
const html = `
<li>enter code here
<div class="collapsible-header grey lighten-4">${ title }</div>
<div class="collapsible-body white">${ content }</div>enter code here
</li>
`;
PARENTELEMENT.insertAdjacentHTML('beforeend', html);

I have change div.insertAdjacentElement to div.insertAdjacentHTML:
and it will work for me

Related

Clever Programmer Javascript tutorial Age in Days Challenge

For the age in Days challenge in this video, I'm getting the following error:
Uncaught TypeError: Cannot read properties of null (reading 'appendChild') at yearBorn (script.js:10:47) at HTMLButtonElement.onclick (challenge.html:19:64) yearBorn # script.js:10 onclick # challenge.html:19
JS:
function yearBorn() {
var birthYear = prompt('What year were you born?');
var ageInDays = (2022 - birthYear) \* 365;
var h1 = document.createElement('h1');
var textAnswer = document.createTextNode('You are ' + ageInDays + ' days old');
h1.setAttribute('id', 'yearBorn');
h1.appendChild(textAnswer);
document.getElementById('flex-box-result').appendChild(h1);
html:
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link
rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
/>
<title>Javascript Challenge</title>
<link rel="stylesheet" href="static/css/index.css"
</head>
<body>
<div class="container-1">
<h2>Challenge 1: Your Age in Days</h2>
<div class="flex-box-container-1">
<div>
<button class="btn btn-primary" onclick="yearBorn()">Click Me</button>
</div>
<div>
<button class="btn btn-danger">Reset</button>
</div>
</div>
<div class="flex-box-container-1">
<div class="flex-box-result"></div>
</div>
</div>
<script src="static/js/script.js"></script>
</body>
</html>
Why am I getting the error?
I was expecting the age in days to print to the flex box container below the buttons in the document. Instead, getting the error
Solution 1
The error in this line
document.getElementById('flex-box-result').appendChild(h1)
Because document.getElementById() need an id which you provide when creating html element like this
<div id="id"></div>
Your flex-box-result is a class
<div class="flex-box-result"></div>
to
<div class="flex-box-result"></div>
Solution 2
In JavaScript code, you can also use a querySelector method with the selector of your element (like CSS selector)
document.querySelector('.flex-box-result').appendChild(h1)

forEach method not setting style property for list items

Here is app.js
const listItems=document.querySelector(".student-list").children;
const numberOfItems=10;
const page=document.querySelector(".page");
displayPage=(list,pageNumber)=> {
const SI=(pageNumber*numberOfItems)-numberOfItems
const EI=pageNumber*numberOfItems
Array.of(list).forEach((item,index)=> {
if (index>= SI && index<EI) {
item.style.display="block";
} else {
item.style.display="none";
}
})
}
addPaginationLinks=(list)=> {
const pages=list.length/10
let html=``
for (let i=0; i<pages; i++) {
html+=`
<li>
<a class="active" href="#">${i+1}</a>
</li>`
return html
}
ul=document.createElement("UL");
ul.innerHTML=html;
div=document.createElement("DIV");
div.className.add("pagination");
div.appendChild(ul);
page.appendChild(div);
}
displayPage(listItems, 1);
addPaginationLinks(listItems);
Here is a sample of index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>Students</title>
<link rel="stylesheet" href="css/reset.css">
<link rel="stylesheet" href="css/design.css">
</head>
<body>
<div class="page">
<div class="page-header cf">
<h2>Students</h2>
<!-- dynamically insert search form here (optional) -->
</div>
<ul class="student-list">
<li class="student-item cf">
<div class="student-details">
<img class="avatar" src="https://randomuser.me/api/portraits/thumb/women/67.jpg">
<h3>iboya vat</h3>
<span class="email">iboya.vat#example.com</span>
</div>
<div class="joined-details">
<span class="date">Joined 07/15/15</span>
</div>
</li>
</ul>
There's no error in the html, it just continues down with more and more li's, and then closes up with a ul and a closing div tag. Then the script app js appears later.
I'm getting an Uncaught TypeError: Cannot set property 'display' of undefined Array.forEach
Basically, it's not recognizing each item in the list in the for each loop. Why is that? When I console log the items, the HTML collection shows up.

Why can't I get my JavaScript replace function to work?

I've been trying for quite a while to get my text to replace and it just hasn't been replacing anything no matter what I try. I've tried searching everywhere but I can't find an answer.
<html>
<head>
<meta charset="UTF-8">
<title>OnStream</title>
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=0">
<link rel="stylesheet" href="https://onstreamvideo.github.io/css/style.css">
</head>
<script language="JavaScript">
function showInput() {
document.getElementById('display').innerHTML =
document.getElementById("sharingurl").value;
}
</script>
<script>
function fetchCorrections() {
var str = document.getElementById("sharingurl").innerHTML;
var res = str.replace(/www.google.com/g, "google");
document.getElementById("sharingurl").innerHTML = str;
}
</script>
<body onload="fetchCorrections();">
<header>
<h1>OnStream</h1>
</header>
</body>
<ul>
<li>
<form>
Dropbox Share Url:<br>
<input type="text" id="sharingurl" value="url"><br><br>
<input type="button" onclick="showInput();" value="Click"><br/>
<br>
</form>
</li>
</ul>
<ul>
<li>
<label>Your Input</label>
<p><span id='display'</span></p>
</li>
<ul>
</body>
</html>
I'm new to Stack Overflow and coding in general so please excuse my ignorance if I made a mistake. :)
EDIT:
Sorry guys, I'm tired and I've been working on this randomly throughout the day trying to pick up where I left off each time and I left a few errors in my code before posting. I tried cleaning up my code a little bit, and I've swapped the code above for the newer more clean code; if you see any mistakes feel free to let me know and just understand it was a clumsy mistake on my part. Thanks.
Try this out, it will work
<html>
<head>
<meta charset="UTF-8">
<title>OnStream</title>
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=0">
<link rel="stylesheet" href="https://onstreamvideo.github.io/css/style.css">
</head>
<script language="JavaScript">
function showInput() {
document.getElementById('display').innerHTML =
document.getElementById("sharingurl").value;
}
function fetchCorrections() {
showInput();
var str = document.getElementById("sharingurl").value;
var res = str.replace(/blue/g, "red");
document.getElementById("sharingurl").value = res;
}
</script>
<body class="depiction">
<header>
<h1>OnStream</h1>
</header>
</body>
<body>
<ul>
<li>
<form>
Dropbox Share Url:
<br>
<input type="text" id="sharingurl" value="url">
<br>
<br>
<input type="button" onclick="fetchCorrections()" value="Click">
<br/>
<br>
</form>
</li>
</ul>
<ul>
<li>
<label>Your Input</label>
<p><span id='display' </p>
</li>
<ul>
</body>
</html>
Mistakes in your programs
Span with id= display is incomplete.
Input element doesn't have property like innerHTML.
You should use value property instead of innerHTML to assign value in input element.
multiple body tags.
And try to replace this function with fetchcorrection
function fetchCorrection(){
var str = document.getElementById("sharingurl").value;
var res = str.replace(/blue/g, "red");
document.getElementById("sharingurl").value = res;
}

Simple Javascript error that is driving me insane

This is driving me nuts. I have put the html and javaScript code below. Whenever I refresh my page I get Uncaught TypeError: screen.addEventListener is not a function. I insert any other variable or ID for screen and it works fine.
HTML Code
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<title>Calculator</title>
<link rel="stylesheet" href="css/reset/reset.css">
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div id="calculator">
<div id="screen">
</div>
<div id="layout">
<ul id="first-row" class="btn-row">
<li><button>C</button></li>
<li><button>=</button></li>
</ul>
<ul id="sec-row" class="btn-row">
<li><button>7</button></li>
<li><button>8</button></li>
<li><button>9</button></li>
<li><button>+</button></li>
</ul>
<ul id="third-row" class="btn-row">
<li><button>4</button></li>
<li><button>5</button></li>
<li><button>6</button></li>
<li><button>-</button></li>
</ul>
<ul id="fourth-row" class="btn-row">
<li><button>1</button></li>
<li><button>2</button></li>
<li><button>3</button></li>
<li><button>*</button></li>
</ul>
<ul id="fifth-row" class="btn-row">
<li><button>0</button></li>
<li><button>/</button></li>
</ul>
</div>
</div>
<script src="js/app.js">
</script>
</body>
</html>
JavaScript Code
var screen = document.getElementById('screen');
var btn = document.getElementsByTagName('button');
var clear = btn[0];
var equals = btn[1];
var seven = btn[2];
clear.addEventListener('click', here);
screen.addEventListener('click', function(){
alert('wth');
});
You have a naming issue. It is clashing with the window.screen object
console.log(window.screen);
MDN window.screen
Rename the variable to something else and it works fine.
var screenX = document.getElementById("screen");
screenX.addEventListener("click", function() { alert("x"); });
<div id="screen">Click</div>
or take it out of global scope
(function () {
var screen = document.getElementById("screen");
screen.addEventListener("click", function() { alert("x"); });
}());
<div id="screen">Click</div>

scribd set page not working

I am using scribd to display pdf. By clicking on the Page 3,Middle,End links the corresponding pages should load. But the pages are not loading properly. And in FF i am not getting any errors. But in chrome console i am getting this error. Failed to execute 'postMessage' on 'DOMWindow': The target origin provided ('http://www.scribd.com') does not match the recipient window's origin ('https://www.scribd.com'). Can anyone help me out in this?
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>Scribd Javascript API Demo</title>
<script type="text/javascript" src='https://www.scribd.com/javascripts/scribd_api.js'></script>
</head>
<body>
<div id="container">
<div id='col1'>
<div id='embedded_doc'><a href='https://www.scribd.com'>Scribd</a></div>
</div>
<div id='col2'>
<h2 id="header"> Loading Document... </h2><br/>
<span id="author"></span>
<div id="bookmarks">
<h4>Bookmarks</h4>
<ul>
<li>Page 3</li>
<li>Middle</li>
<li>End</li>
</ul>
</div>
<div id="comment"></div>
</div>
<div class="clearfix"> </div>
</div>
<script type="text/javascript">
// Data
// Instantiate iPaper
var scribd_doc = scribd.Document.getDoc(2520449, 'key-1127428tb3rbejns9bhr');
// Parameters
scribd_doc.addParam('height', 420);
scribd_doc.addParam('width', 530);
scribd_doc.addParam('auto_size', true);
scribd_doc.addParam('mode', 'slideshow');
scribd_doc.addParam('jsapi_version', 2);
// Write the instance
scribd_doc.write('embedded_doc');
// Bookmark Helpers
var goToPage = function(page) { alert(scribd_doc.api.getPageCount());
if (scribd_doc.api){
scribd_doc.api.setPage(3);
}
}
var goToMiddle = function() {
if (scribd_doc.api){
goToPage( Math.floor(scribd_doc.api.getPageCount()/2) );
}
}
var goToEnd = function() {
if (scribd_doc.api) {
goToPage(scribd_doc.api.getPageCount());
}
}
</script>
View Source and you'll see that this is all dynamically generated using the Scribd Javascript API.
</body>
</html>
I fixed this issue by downloaded the scribd_api.js file and modified the path to https in js. And now the set page is working without any errors.

Categories

Resources