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>
Related
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>
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');
I'm really new at this and I need a random button on my page that would show a new line of information in a div every time someone click on the random button. I was also wondering if there is over 800 lines is it possible to put it in an outside file as txt or html.
Here is what I got so far and well it doesn't work and I'm getting confuse... Please help
<script type="text/javascript" src="jquery-2.2.0.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#text').hide();
$('a#random').click(function(){
$('#text').toggle();
})
function RndText() {
var rannum= Math.floor(Math.random()*textarray.length);
document.getElementById('#text').innerHTML=textarray[rannum];
}
var textarray = [
"Hello",
"How are you",
"Good Bye"
];
$("#text").load()
})
</script>
<body>
<div id="text">Line to Show</div>
RANDOM
</body>
Uh. Pretty much this:
$('a#random').click(function(){
$('#text').toggle();
RndText(); //you're good
});
Although I will point out that RndText() uses document.getElementById when it could use $("#text") instead. (there's a .html() method that will write the value instead of the .innerHTML property).
document.getElementById is also not currently working because you used "#text" instead of "text", jQuery uses CSS selectors, getElementById does not.
Add execution of RndText when you clicks on Random button.
$('a#random').click(function(){
$('#text').show();
RndText();
})
This will give you a button and you can run this code by clicking the button below. However, I did not quite understand you second part of the question: 800 lines in separate file, what do you wanna do with it? Tell me so that I can helo you further...
Editted:
<?php
$data = file_get_contents('demo.txt');
$lines= split("\n",$data);
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script type="text/javascript">
var textarray = <?php echo json_encode($lines); ?>;
function RndText() {
var rannum= Math.floor(Math.random()*textarray.length);
$('#text').text(textarray[rannum]);
console.log(textarray[rannum]+" "+rannum+" "+textarray.length);
}
$(document).ready(function(){
$('#text').hide();
$('#random').click(function(){
$('#text').show();
RndText();
});
});
</script>
<body>
<div id="text"></div>
<button id="random">RANDOM</button>
</body>
I have this simple code that shows an image and a word and you have to complete the field. If you write the word correctly, a congrats popup comes up.
I was able to figure out how to randomize items in an array to display a random image.
Now I want to check on each keyup if it matches that random word.
It seems there's something wrong with my IF statement because if I remove it, popup works perfectly.
Error:
uncaught typeerror undefined is not a function
Code:
<html>
<head>
<title>AutistApp</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
<script src="js/jquery.min.js"></script>
</head>
<body>
<div id="container">
<div class="eval">CORRECTO</div>
<div class="siguiente">¡OTRA VEZ!</div>
<div class="dibujo"><img id="dibujito" src="img/apple.png" /></div>
<div class="palabra">MANZANA</div>
<div class="respuesta"><input type="text" id="resp" name="resp" value=""/>
</div>
</div>
<script type="text/javascript">
/***** RANDOM VALUES *****/
var messages = ["manzana", "pera", "banana"],
message = messages[Math.floor(Math.random() * messages.length)];
$('.palabra').text(message);
$('#dibujito').attr('src','img/'+message+'.png');
/***** KEYDOWN CHECK *****/
$(document).ready(function(){
$('#resp').keyup(function(){
if ($("#resp").value() == message) {
$('.eval').slideDown();
$('.eval').delay(3000).fadeOut();
$('.siguiente').delay(3000).slideDown();
}
});
});
</script>
</body>
</html>
You need to use .val() instead of .value() to get the value of input element, so you can do:
if ($("#resp").val() == message) {
instead of:
if ($("#resp").value() == message) {
You also need to wrap all of your code inside DOM ready handler:
$(document).ready(function () {
var messages = ["manzana", "pera", "banana"],
message = messages[Math.floor(Math.random() * messages.length)];
$('.palabra').text(message);
$('#dibujito').attr('src', 'img/' + message + '.png');
$('#resp').keyup(function () {
if ($("#resp").val() == message) {
$('.eval').slideDown();
$('.eval').delay(3000).fadeOut();
$('.siguiente').delay(3000).slideDown();
}
});
});
Folks you need to use
$("#resp").val()
in if condition.
Here is my code that is not working - thanks guys - first question!
<html>
<head>
<script type="text/javascript">
var x =document.getElementById("myElementId").innerHTML;
</script>
</head>
<body>
<div id="myElementId">24</div>
<div>
<script type="text/javascript">
if (x < 25) {
document.write("worked")
}
else {
document.write("didn't work")
}
</script>
Also sorry for the update but do you guys have an idea of how to do this when the div is in an iframe thats not on the same domain? Thanks
This line
var x = document.getElementById("myElementId").innerHTML;
is executed before the element with ID myElementId exists, so JavaScript cannot find it (getElementById returns null).
Put it after the element:
<div id="myElementId">24</div>
<script>
var x = document.getElementById("myElementId").innerHTML;
</script>
The HTML document is processed from top to bottom.
You're running this line:
var x =document.getElementById("myElementId").innerHTML;
before the element exists. Remove the script from the head an put that line right before:
if(x < 25) {
Instead.
In addition to the creating the element first,
I believe innerHtml returns a string value
Try parsing it first;
var value = document.getElementById("myElementId").innerHTML;
var x = parseInt(value,10)
change it to:
<html>
<head>
</head>
<body>
<div id="myElementId">24</div>
<div>
<script type="text/javascript">
var x =document.getElementById("myElementId").innerHTML;
if (x < 25) {
document.write("worked")
}
else {
document.write("didn't work")
}
</script>
the element that you are trying to look for does not even exist on the page when you run the script that is why you have run into this issue..
document.getElementById("myElementId").innerHTML;
You have to use a # with Id and . with class in it
document.getElementById("#myElementId").innerHTML;