Categories
JavaScript Answers

How to load an HTML page in a div using JavaScript?

To load an HTML page in a div using JavaScript, we set the innerHTML property.

For instance, we write

document.getElementById("content").innerHTML =
  '<object type="text/html" data="home.html" ></object>';

to select the wrapper element with getElementById.

And then we set its innerHTML property to a string with an object element that loads the home.html page.

Categories
JavaScript Answers

How to scroll to top of page with JavaScript?

To scroll to top of page with JavaScript, we set the scrollTop property of the body element to 0.

For instance, we write

document.body.scrollTop = document.documentElement.scrollTop = 0;

to set document.body.scrollTop and document.documentElement.scrollTop to 0 to scroll to the top of the page.

Categories
JavaScript Answers

How to replace text inside a div element with JavaScript?

To replace text inside a div element with JavaScript, we set the innerHTML property.

For instance, we write

fieldNameElement.innerHTML = "My new text!";

to set the innerHTML property of the fieldNameElement element to the new text content.

Categories
JavaScript Answers

How to fix Error: Failed to execute ‘appendChild’ on ‘Node’: parameter 1 is not of type ‘Node’ with JavaScript?

To fix Error: Failed to execute ‘appendChild’ on ‘Node’: parameter 1 is not of type ‘Node’ with JavaScript, we should make sure we call appendChild with a valid node.

For instance, we write

const z = document.createElement("p");
z.innerHTML = "hello";
document.body.appendChild(z);

to create a p element node with createElement.

And then we set its innerHTML property to 'hello'.

Finally, we call document.body.appendChild to append the z element as the last child of the body element.

Categories
JavaScript Answers

How to open window.location in new tab with JavaScript?

To open window.location in new tab with JavaScript, we call the window.open method.

For instance, we write

window.open("https://example.com", "_blank");

to call window.open with the URL to open and '_blank' to open the URL in a new window or tab.