Fetching HTML and changing document body - javascript

Please, do not mark this as a duplicate. I tried everything I could, and this isn't working. I have experience in Javascript. It isn't my first time using it
Index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>JUST_LOAD_ALREADY</title>
<!-- <script defer src="/index.js"></script> -->
</head>
<body>
PLEASSDETY FGUIRWFVUI
<script>
function loadContent() {
fetch("/content.html")
.then((res) => res.text())
.then((text) => (document.body.innerHTML = text));
}
loadContent()
</script>
</body>
</html>
content.html:
<h1>Content page</h1>
Expected page content inside body after everything loads:
<h1>Content</h1>
Actual page content inside body:
PLEAS
Its neither my frustration text nor content.html's content. This is killing me please help tell me why this is happening. These are the only two files I have + a package.json for running sirv

Adding a div with an id and changing its innerHTML seems to work, could be "killing yourself" due to having the script inside the body like #MarkusZeller said. The code below worked:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>JUST_LOAD</title>
<!-- <script defer src="/index.js"></script> -->
</head>
<body>
PLEASSDETY FGUIRWFVUI
<main id="content"></main>
<script>
function loadContent() {
fetch("/content.html")
.then((res) => res.text())
.then((text) => (document.getElementById("content").innerHTML = text));
}
loadContent();
</script>
</body>
</html>

Alternatively put this in the head
window.addEventListener("load",() => {
fetch("/content.html")
.then(res => res.text())
.then(text => document.body.innerHTML = text);
})

Related

How to get the data received from Json to a variable for output to the site?

Can you please tell me how to transfer the data received from Json to a variable for output to the site?
I receive the data and output it to the page (for clarity), then it is necessary to transfer it to a variable for processing and output.
Next, the "showData()" function displays the received data on the site.
Thank you in advance!
let testBox = document.querySelector('.goods .container');
// get data
function getData() {
fetch('https://jsonplaceholder.typicode.com/posts')
.then(response => response.text())
.then(text => testBox.innerHTML = text)
};
// show data
let allGoods = getData(); // how to pass data to a variable?
function showData() {
let outGoods = '';
for (let key in allGoods) {
outGoods += `
<div class="goods__item">
<a><img src="${allGoods[key].image}"/></a>
<div class="goods__tx">
<h2>${allGoods[key].name}</h2>
<p>${allGoods[key].desc}</p>
<span>${allGoods[key].availability}</span>
<div class="goods__bottom">
<b>${allGoods[key].price} $</b>
<div class="goods__btn">
<button class="goods__minus" data-id="${key}">-</button>
<button class="goods__plus" data-id="${key}">+</button>
</div>
</div>
</div>
</div>`
}
let goodsContent = document.querySelector('.goods .container');
goodsContent.innerHTML = outGoods;
}
showData();
<!DOCTYPE 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="icon" href="img/js.png" sizes="64x64">
<link rel="stylesheet" href="css/style.css">
<title>Document</title>
</head>
<body>
<section class="goods">
<div class="container"></div>
</section>
<section class="cart">
<div class="container"></div>
</section>
<script src="db.json"></script>
<script src="script.js"></script>
</body>
</html>

Javascript not firing when page is loaded in a div

So I have this issue, I want to use vanilla JavaScript because I don't like how bloated JQuery is. Now, the problem I have is when I load my file into the div withe the following code:
async function loadPage (pagename) {
await fetch(pagename, {
headers: {
"Content-Type": "text/html; charset=utf-8"
}
})
.then((response) => response.text())
.then((html) => {
document.getElementById("Loader").innerHTML = html;
})
.catch((error) => {
console.warn(error);
});
}
my JavaScript in the page doesn't fire.
I have tried running JavaScript in the file and also with external files.
When I put the JavaScript file for this HTML in the main page it fires, but it is littered with errors. When I use the JQuery load function it works fine though, is there any way to get this right in vanilla JavaScript or am I gonna have to use JQuery??
HTML for details.html:
<!DOCTYPE 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="css/autocomplete.css">
<link rel="stylesheet" href="css/details.css">
<link rel="stylesheet" href="css/tablestyles.css">
<title>Search</title>
</head>
<body>
<!-- Enter search criteria here -->
<div id="top">
<button onclick="search();">Search</button>
<div class="autocomplete" style="width:300px;">
<input type="text" name="searchPhrase" id="searchPhrase" placeholder="Search Phrase" autocomplete="off">
</div>
<!-- Options for autocomplete -->
<div id="displaydiv">
</div>
</div>
<div id="results">
</div>
</body>
<script src="js/autocomplete_input.js"></script>
<script src="js/tablecreator.js"></script>
<script src="js/details.js"></script>
</html>
loadPage is called by main.js
function openSearch(){
loadPage('details.html');
}
I tried replicating it in codesandbox!

How to change the styling of an element using JS when it has no class or ID?

I have a html file (converted from docx) and it does not have any class names or ids. How can I style it using JS? For example, if I need to change the color of the heading for the below file HTML
<!DOCTYPE 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" />
<script src="./script.js"></script>
<title>Document</title>
</head>
<body>
<h1>This is the heading</h1>
<p>Hello, my name is xyz and this is a para</p>
</body>
</html>
This is what I tried, but document.getElementByTagName() does not return the element like document.getElementById()
console.log('hello world');
Heading = document.getElementsByTagName('h1');
console.log(Heading);
Heading.style.color = 'blue';
Edit:
I tried the below code, but it returns undefined
console.log('hello world');
Heading = document.getElementsByTagName('h1')[0];
console.log(Heading);
Heading.style.color = 'blue';
You can try document.querySelector() as well.
<!DOCTYPE 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" />
<title>Document</title>
</head>
<body>
<h1>This is the heading</h1>
<p>Hello, my name is xyz and this is a para</p>
</body>
<script type="text/javascript">
const header = document.querySelector('h1');
console.log(header);
header.style.color = 'blue';
</script>
</html>
One other thing to note is - we need to wait for the page to load, otherwise your javascript code runs first and returns undefined.
You can ensure javascript to run after page load using any of the below ways -
Add an event listener – document.addEventListener("load", FUNCTION);
Add onload to the body tag – <body onload="FUNCTION()">
Defer the script – <script src="SCRIPT.js" defer>
Lastly, place the script at the very bottom of the page – Although this is not quite “after page load”.
The issue in your code is that getElementsByTagName returns an array, but you're using is as if it were a single element.
Try this:
window.addEventListener('load', () => {
const heading = document.querySelector('h1');
heading.style.color = 'blue';
});
<h1>This is the heading</h1>
<p>Hello, my name is xyz and this is a para</p>
Please update your code like this. you imported the script before html.
There are two solutions. first you have to import script after html or use
window.addEventListener
window.addEventListener('load', () => {
const heading = document.querySelector('h1');
heading.style.color = 'blue';
});
<h1>This is the heading</h1>
<p>Hello, my name is xyz and this is a para</p>

Unable to display JSON data on HTML

I am trying to display data randomly in my file 'question.json' on HTML but somehow there's nothing happened. I'm starting to learn JavaScript and still don't know how to fix. Here's my code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Answer Something</title>
<script>
$.getJSON('question.json', function(data){
console.log(data)
let questionList = data[Math.floor(Math.random()* data.length)];
let display = document.getElementById('question');
display.innerHTML = questionList;
});
</script>
</head>
<body>
<nav>
Quick Ask
Quick Answers
</nav>
<h1 id="question"></h1>
<div>
<button>Sai/Không/Trái</button>
<button>Đúng/Có/Phải</button>
</div><br>
<div>
<button>Kết quả vote</button>
<button>Câu hỏi khác</button>
</div>
</body>
</html>

Aloha Editor does not work on Opera, and sometimes does not work on Chrome

I've been using Aloha Editor to create an example of a simple editor, but I haven't succeed to getting it to work in Opera. The menu doesn't appear and the textarea is not editable.
In all other browsers seems to work fine, but sometimes Chrome needs to refresh the page to work.
This is the relevant HTML code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link href="//cdn.aloha-editor.org/latest/css/aloha.css" rel="stylesheet" media="screen" />
</head>
<body>
<textarea id="content"></textarea>
<script src="//cdn.aloha-editor.org/latest/lib/require.js"></script>
<script src="//cdn.aloha-editor.org/latest/lib/aloha.js" data-aloha-plugins="common/ui,common/format,common/table,common/list,common/link,common/block,common/undo,common/contenthandler,common/paste"></script>
<script src="notes.js"></script>
</body>
</html>
And this is the javascript code (inside notes.js):
var Aloha = window.Aloha || ( window.Aloha = {} );
Aloha.settings = { sidebar: { disabled: true } };
Aloha.ready(function () {
Aloha.jQuery('#content').aloha();
});
I'm answering my own question after reading the comment from Inshallah.
The problem was that the JavaScript variables Aloha and Aloha.settings should be set before including Aloha.
HTML code
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link href="//cdn.aloha-editor.org/latest/css/aloha.css" rel="stylesheet" media="screen" />
</head>
<body>
<textarea id="content"></textarea>
<script src="//cdn.aloha-editor.org/latest/lib/require.js"></script>
<script>
var Aloha = window.Aloha || ( window.Aloha = {} );
Aloha.settings = { sidebar: { disabled: true } };
</script>
<script src="//cdn.aloha-editor.org/latest/lib/aloha.js" data-aloha-plugins="common/ui,common/format,common/table,common/list,common/link,common/block,common/undo,common/contenthandler,common/paste"></script>
<script src="notes.js"></script>
</body>
</html>
JavaScript code (inside notes.js)
Aloha.ready(function () {
Aloha.jQuery('#content').aloha();
});

Categories

Resources