I am trying to print a text on the current element. I tried these two codes, but they doesn't seem to work:
This one is printing the text in the whole document:
<div>
<script>
fetch('file.txt').then((resp) => resp.text()).then(function(data) {
document.write(data);
});
</script>
</div>
Resulting in this:
<html>
<body>
<!-- THE TEXT THAT I REQUESTED APPEARS HERE -->
</body>
</html>
And the code below is returning the following error:
<div>
<script>
fetch('file.txt').then((resp) => resp.text()).then(function(data) {
document.this.innerHTML(data);
});
</script>
</div>
Cannot read property 'innerHTML' of undefined
Replace this with body. innerHTML is not a function its a property you need to set it.
I think you want to append to the <div> in which the <script> us present. You can access the script and get its parentNode
<div>
<script>
const script = document.scripts[document.scripts.length - 1];
fetch('file.txt').then((resp) => resp.text()).then(function(data) {
script.parentNode.innerHTML = data;
});
</script>
</div>
Note:document.scripts[document.scripts.length - 1] will get the current <script> tag because it will be lastest script executed.
You can use document.writeln() to write within the current div
<div>
<script>
fetch('file.txt').then((resp) => resp.text()).then(function(data) {
document.writeln(data);
});
</script>
</div>
Hre is a similar example demonstrating the result.
<div>
<script>
Promise.resolve('abc123<br>xyz789')
.then(function(data) {
document.writeln(data)
});
</script>
</div>
First you should move the script out of the div and then replace 'this' in your code with a reference to the target div.
If you give your div an id of 'target' you could do the following:
const target = document.getElementById('target');
fetch('file.txt').then((resp) => resp.text()).then((data) => target.innerHTML = data);
Related
I would like to rename a h1 text in the header for any single page, is it possible with a script?
The line of the title is:
Like this
I wrap in a page load event and then use the closest known selector
If you have class="titoloheader" the code is even simpler than using
div[data-row=middle] h1
If you want to change only on pages with /articoli/ you can test pathname:
const url = new URL(location.href);
if (url.pathname.split("/").indexOf("articoli") !=-1) {
document.querySelector("h1.titoloheader").innerText = "Hello"
}
})
If you want to change on page-id-X, you can do this:
Vanilla JS
const pageTitles = {
"41": "Hello",
"44": "Goodbye",
"47": "Ciao",
"3": "Arriverderci",
"313": "Hey",
"316": " Bye",
"318": " This is silly",
"50": "The end"
};
const changeHeader = () => {
let id = [...document.body.classList] // all the classes of the body tag
.filter(classStr => classStr.startsWith("page-id")); // find the one that starts with page-id
if (id.length)[, , id] = id[0].split("-") // if found (an array) grab the last part after last -
if (id && Object.keys(pageTitles).includes(id)) { // do we find that ID in the list
document.querySelector("h1.titoloheader").innerText = pageTitles[id]; // change the header
}
};
window.addEventListener("load", changeHeader); // when the page loads
<body class="home page-template-default page page-id-47 logged-in admin-bar no-customize-support ct-loading" data-link="type-1" data-forms="classic">
<div data-row="middle" data-columns="1">
<div class="ct-container">
<div data-column="middle">
<div data-items="">
<div class="ct-header-text " data-id="text">
<div class="entry-content">
<h1 class="titoloheader">Benvenuti</h1>
</div>
</div>
</div>
</div>
</div>
</div>
jQuery
const pageTitles = {
"41": "Hello",
"44": "Goodbye",
"47": "Ciao",
"3": "Arriverderci",
"313": "Hey",
"316": " Bye",
"318": " This is silly",
"50": "The end"
};
const changeHeader = () => {
let id = [...document.body.classList] // all the classes of the body tag
.filter(classStr => classStr.startsWith("page-id")); // find the one that starts with page-id
if (id.length)[, , id] = id[0].split("-") // if found (an array) grab the last part after last -
if (id && Object.keys(pageTitles).includes(id)) { // do we find that ID in the list
$("h1.titoloheader").text(pageTitles[id]); // change the header
}
};
$(document).ready(changeHeader);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body class="home page-template-default page page-id-47 logged-in admin-bar no-customize-support ct-loading" data-link="type-1" data-forms="classic">
<div data-row="middle" data-columns="1">
<div class="ct-container">
<div data-column="middle">
<div data-items="">
<div class="ct-header-text " data-id="text">
<div class="entry-content">
<h1 class="titoloheader">Benvenuti</h1>
</div>
</div>
</div>
</div>
</div>
</div>
To change the text of the h1 element in your example when the page loads, you can use:
window.addEventListener('load', event => {
const h1Element = document.querySelector("#main-container .entry-content h1");
h1Element.innerText = 'New H1 Text';
});
If you don't make the change to the H1 in the window load event callback, the element you're targeting likely won't be available in the DOM when you try to access it with document.querySelector.
jQuery:
$('#main-container div[data-row="middle"] .entry-content h1').html('Your New Title');
Vanila JS:
var el = document.querySelector("#main-container div[data-row="middle"] .entry-content h1");
el.innerHTML= "Your New Title";
Sometimes text can be replaced using pure CSS
See the collection of answers here:
How can I replace text with CSS?
Cons:
Doesn't supported by all browsers, check your requirements and
browser compatibility list.
Old text will remain hidden, can be
problem for some screen reader.
Pros:
Sometimes you cannot inject your JavaScript directly.
Here is a simple example from W3 schools
<!DOCTYPE HTML>
<html>
<body>
<h1 id="myHeader">Hello World!</h1>
<button onclick="displayResult()">Change text</button>
<script>
function displayResult() {
document.getElementById("myHeader").innerHTML = "Have a nice day!";
}
</script>
</body>
</html>
If you notice, they add a unique id to the h1 tag. This way way you can access the tag directly.
https://www.w3schools.com/tags/att_id.asp
what's the problem here? When I run this code I get undefined error
<div>
<span>ali</span>
<span>veli</span>
<span>deli</span>
</div>
<script>
var x = $("div").children();
alert(x[0].text);
</script>
You get undefined because there is no HTML DOM property named text. Maybe you wanted to use innerText property, e.g.:
var x = $("div").children();
alert(x[0].innerText);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<span>ali</span>
<span>veli</span>
<span>deli</span>
</div>
<html>
<head>
<script src="edvTextGame.js"></script>
<link rel="stylesheet" href="placeholder.css">
</head>
<div class="firstScreen">
<div class="Title Fade">Placeholder</div>
<button class="Fade" onclick="setTimeout(Start)"> Start </button>
</div>
<div class="introStoryScreen">
<div class="JSGameText">
<p id="intro" ></p>
</div>
</div>
</html>
The used HTML
window.onerror = function(msg, url, linenumber) {
alert('Error message: '+msg+'\nURL: '+url+'\nLine Number: '+linenumber);
return true;
}
//FUNCTIONS
// Intro sequence
function Start() {
document.getElementById("intro").innerHTML = test;
}
// Creator. -> Origin asign, name asign, stat asign
function CharCreation() {
}
The used JavaScript
The problem in these files is that the document.getElementById part is not functioning, it gives me an empty error.
My notepad++ also doesn't recognize/autofill when I type .innerHTML behind the document.getElementById part.
According to examples i've seen, this should work. Can someone help me out?
The error message will probably be about the assignment... what does 'test' reference to?
Maybe you meant:
document.getElementById("intro").innerHTML = "test";
Use the body.onload function to ensure that the document was loaded and ready, then set the value. Note that by default, Javasciprt expects enclosed strings, or variables on operations.
function aFunction(){
var aString = "test"
document.getElementById("intro").innerHTML = aString;
}
<body onload="aFunction()">
You are missing the quotes in test :
function Start() {
document.getElementById("intro").innerHTML = "test";
}
I found the problem, in the HTML I was trying to add what I wanted to add to a P tag, I got rid of the P tag and made it write to the DIV tag instead, it works now.
I have the following code and I want to remove placeholder.
<div class="myclass">
<p>[Sitetile][change this too]someothercontent</p>
</div>
and I want to change the above markup to this with some event using jQuery:
<div class="otherclass">
<p>changemaincontentchangesomeothercontent</p>
</div>
Create an object with the index named as the part you want to replace (inside the brackets) and assign the value to it. Then use the $.each-function to iterate over the object and replace the values in the html with the one from the object. After that assign the new html-string to your element.
var change = {
'Sitename': 'yahoo.com',
'Sitetile': 'changemaincontent',
'change this too': 'change'
};
var $elem = $('.myclass > p'); //cache the element
var html =$elem.html(); //get the html-string
$.each(change, function(index, value){ //iterate over the object
html = html.replace('[' + index + ']', value); //replace the values
});
$elem.html(html); //assign the new html-string
Demo
Reference
.replace()
$.each()
.html()
you need to put someothercontent in <span>
HTML
<div class="myclass">
<p>
maincontent
<span>someothercontent</span>
</p>
</div>
Script
$('.myclass').find('a').text('changemaincontent');
$('.myclass').find('span').text('changesomeothercontent');
Demo
You can try some thing like this !!!
<<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div id='link'><a href='javascript:open_fun()'>OPEN</a></div>
</body>
</html>
<script type="text/javascript">
function close_fun() {
document.getElementById('link').innerHTML = "<a href='javascript:open_fun()'>OPEN</a>";
}
function open_fun() {
document.getElementById('link').innerHTML = "<a href='javascript:close_fun()'>CLOSE</a>";
}
</script>
Hope this helps !!!
I have 2 HTML files namely a.html and b.html, One js file namely do.js.
Here are each the contents of each file:
a.html:
<head>
<script src="do.js" type="text/javascript"></script>
</head>
<body>
<button onClick = "doWork();">click me</button>
<iframe src = "b.html" id = "previewFrame"></iframe>
</body>
b.html (relevant part):
<div id = "container"></div>
do.js:
function doWork(){
var div = $('#previewFrame').contents().find('#container');
div.html("<input type = 'text' id = 'testElem' value = '12'><script>alert(document.getElementById('testElem').value);</script>");
}
When I run the above code, the content of the iframe gets replaced by the text box, however the alert fails.
I get a "type error" stating that document.getElementById... is null.
Can anyone please tell me what am I missing in the above code?
You are calling the Javascript function using document, but this object is from the parent document, not the document of the iframe, try with:
function doWork(){
var a = $('#previewFrame').contents().find('body');
a.html("<input type = 'text' id = 'testElem' value = '12'><sc"+"ript>alert($('#previewFrame').contents()[0].getElementById('testElem').value);</scr"+"ipt>");
}
See demo here.