How to resolve jquery children method alert error? - javascript

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>

Related

document.getElementByClassName not working together with for-loop

I'm trying to make it so only some specific boxes get padding on the left and right but the code doesn't pass the "getElementByClassName"-part. I get the alert "Test1" but not "Test2" so the problem is somewhere on that line I think.
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script type="text/javascript" >
var numProducts = $('.product').length;
for(var i = 1;i<numProducts;i++){
var x = (i+1)/3;
if(x%1=0){
alert("test1");
var box = document.getElementByClassName('product')[i-1];
alert("test2");
box.style.paddingRight ="30px";
box.style.paddingLeft="30px";
}
}
</script>
I get the right values from numProducts, i and x so I don't think they are the problem. What am I supposed to do? Thanks
What you expected should be document.getElementsByClassName rather than document.getElementByClassName.
The following is my version of your script. I would recommend that you actually use jQuery, as you have clearly loaded it already. And using jQuery means that something like document.quersSelectorAll() is not needed anymore.
$('.product').each(function(i){
i%3==2 && $(this).addClass("padded")
})
.padded {padding-right:30px;
padding-left:30px;}
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<div class="product">a</div>
<div class="product">b</div>
<div class="product">c</div>
<div class="product">d</div>
<div class="product">e</div>
<div class="product">f</div>
<div class="product">g</div>
<div class="product">h</div>
<div class="product">i</div>

How to change the innerHTML of the current element?

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);

workaround for innerHTML = 'null' when window loads

I'm building an app with ES5 JS just for practice and "fun" where I store websites in localStorage then print them out on the page, i.e. a bookmarker application.
I'm getting a
TypeError: Cannot set property 'innerHTML' of null
error in the console when I run the following code:
index.html
<body onload="fetchBookmarks()">
<div class="container">
...some code
</div>
<div class="jumbotron">
<h2>Bookmark Your Favorite Sites</h2>
<form id="myForm">
...some code
</form>
</div>
<div class="row marketing">
<div class="col-lg-12">
<div id="bookmarksResults"></div> /* problem code */
</div>
</div>
<footer class="footer">
<p>© 2018 Bookmarker</p>
</footer>
</div>
<link rel="stylesheet" href="main.css">
<script src="./index.js"></script>
</body>
index.js
...someJScode that stores the websites in localStorage
function fetchBookmarks() {
var bookmarks = JSON.parse(localStorage.getItem('bookmarks'));
//Get output id
var bookmarksResults = document.getElementById('#bookmarksResults');
bookmarksResults.innerHTML = '';
for(var i = 0; i < bookmarks.length; i++) {
var name = bookmarks[i].name;
var url = bookmarks[i].url;
bookmarksResults.innerHTML += name;
}
}
now, the error is obviously because I am loading the <body> before the <div id="bookmarksResults"></div> so innerHTML responds with null
But two things here:
1) When I assign onload="fetchBookmarks()" to the <footer> element, the function doesn't run.
2) The tututorial I am following has this code almost exactly and it runs there.
I've also tried running the fetchBookmarks() function like this:
window.onload = function() {
fetchBookmarks();
function fetchBookmarks(){
...some JS code
};
}
But that returned the same
TypeError: Cannot set property 'innerHTML' of null
So I'm a bit lost here and am much more interested in figuring out why this isn't working and the theory behind it so I understand JS better (the whole point of building this app in the first place).
Any help would be appreciated! Thanks SO team.
The problem is with this line:
document.getElementById('#bookmarksResults')
You don't need to prefix the ID with # when you're using it with document.getElementById. Either you may remove the # from the method call, or use document.querySelector(), which works the same way, but support CSS-like selectors to select elements from DOM.
document.getElementById('bookmarksResults');
// OR
document.querySelector('#bookmarksResults');
You need to pass the value of the id without the #
Update from
var bookmarksResults = document.getElementById('#bookmarksResults');
to
var bookmarksResults = document.getElementById('bookmarksResults');

Writing to HTML with JavaScript

<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.

Why is my javascript not modifying the html?

Supposed to insert entered text between input field and send button, but it does noting.
<body>        
<section>
<p>passcode: <input type=text id=passcode></p>
<section id=middle></section>
<p><input type=button id=button value=send></p>
</section>
<script type="text/javascript">
var log=new Array();
document.getElementById("button").onclick=exlog();
exlog(){
log.push(document.getElementById("passcode").value)
for(i=0;i<log.length;i++){
document.getElementById("middle").innerHtml=log[i];
}
}
</script>
</body>
Change
document.getElementById("middle").innerHtml=log[i];
to
document.getElementById("middle").innerHTML=log[i];
Reference: https://developer.mozilla.org/en-US/docs/DOM/element.innerHTML
Your exlog function is missing the function keyword and you are setting the onclick handler incorrectly.
Also innerHtml should be innerHTML
document.getElementById("button").onclick=exlog;
function exlog(){
log.push(document.getElementById("passcode").value)
for(i=0;i<log.length;i++){
document.getElementById("middle").innerHTML=log[i];
}
I noticed a couple of problems with your code. Most importantly, you should use innerHTML, not innerHtml (note capitalization).
Additionally, you need to be careful of how you deal with functions. Just putting exlog(){} will not create a function. Instead, you should use the function keyword.
Finally, you want to set the onclick handler to the function exlog. What you have used will actually set the onclick handler to the result of evaluating the exlog function.
Here's a solution with all of the suggested changes:
<body>
<section>
<p>passcode: <input type=text id=passcode></p>
<section id=middle></section>
<p><input type=button id=button value=send></p>
</section>
<script type="text/javascript">
var log=new Array();
document.getElementById("button").onclick=exlog;
function exlog(){
log.push(document.getElementById("passcode").value)
for(i=0;i<log.length;i++){
alert(log[i]);
document.getElementById("middle").innerHTML=log[i];
}
}
</script>
</body>
You are evaluating the function by using it like this: exlog(), since exlog doesn't have a return statement, it evaluates to undefined, which the browser won't execute.
If you want to assign it you can just use it's name exlog
Also, as mentioned by Teemu and Musa, the function keyword was missing from the definition of exlog
Also, the capitalization of innerHTML has to be exact, mixing cases wont work.
<body>
<section>
<p>passcode: <input type=text id=passcode></p>
<section id=middle></section>
<p><input type=button id=button value=send></p>
</section>
<script type="text/javascript">
var log = [];
document.getElementById("button").onclick = exlog; // <== no need to evaluate the function, just assign it.
function exlog(){ // <== as pointed out below function keyword was missing
log.push(document.getElementById("passcode").value);
document.getElementById("middle").innerHTML += log[log.length - 1]; // <== needs to be capitilized exactly like this
}
</script>
</body>

Categories

Resources