This seems like it should be pretty basic, and I can't figure out why it isn't working. I have a super simple page so far and I want to select the paragraphs with JS:
Here's my HTML:
<!DOCTYPE html>
<html>
<head>
<script src="misc.js" type="text/javascript"></script>
</head>
<body>
<p id="first">Just one paragraph.</p>
<p id="second">Two, actually.</p>
</body>
</html>
And my JS:
var paras = document.getElementsByTagName('p');
console.log(paras.length);
I expect the console log to show 2 but I'm seeing 0. I read the documentation pretty closely and I can't figure out what I'm doing wrong here.
At the time you run the script, there are no paragraphs in the document.
Either move the script element so it appears after the paragraphs, or put the code in a function and then call that function later (e.g. when the load event fires).
Related
I've looked at various websites but non have helped. To me everything seems to be correct, but I can't get the
document.getElementByClassName("first").style.display="none";
to work no matter how many times I tried, I kept getting the same error message on JS;
ERROR:'document' is not defined.[no-undef]
Tried defining the 'document' part and didn't help. Maybe, I was doing the connection between external folders incorrect I tried that and nothing changed
HTML:
<html>
<head>
<script src="JS.js"></script>
</head>
<body>
<div class="first">
<p>Hello and welcome to my first page<br>
in this page I will test out new think<br>
and see what works and what doesn't<br>
</p>
</div>
<button type="button" onclick="myFunction">Click me</button>
</body>
</html>
JS:
function myFunction(){
document.getElementsByClassName("first").style.display="none";
The button is suppose to clear all he style's from "first".I've changed many outcomes and have nothing happen to the code just the same error repeating its-self over and over again.
document.getElementByClassName() returns an array of elements, so you'll need the index of the element you want to target.
You should call the function by myFunction() and add [0] to getElementsByClassName to get specific element.
function myFunction() {
document.getElementsByClassName("first")[0].style.display="none";
}
<html>
<head>
<script src="JS.js"></script>
</head>
<body>
<div class="first">
<p>Hello and welcome to my first page<br>
in this page I will test out new think<br>
and see what works and what doesn't<br>
</p>
</div>
<button type="button" onclick="myFunction()">Click me</button>
</body>
</html>
It seams that the error you are recieving comes from a linter, but has nothing to do with your code not working. To fix your linter issue, you might want to have a look at this post.
For errors that are produced at runtime, you should have a look at your browser console (In most cases opened with F12).
In regards to your main issue, there are two things to fix:
1)
Your inline onclick handler should be called like so:
<button type="button" onclick="myFunction()">Click me</button>
2)
Instead of using document.getElementsByClassName() - which returns an array -
I recommend you to use document.querySelector() instead, as it returns just the first element it found and is much easier to use, if you are already familiar with css selectors.
For more information an the querySelector-function have a look at this page.
So, in your code it should look like this:
function myFunction() {
document.querySelector(".first").style.display="none";
}
I know that this is a frequently asked question.
I have tried all the methods like using onload() for body tag,
placing the script after the DOM elements and using self invoking function.
Yet I get that my element is undefined.
P.S: document.getElementsByTagName('') replaced with document.getElementById('') works fine. Why is that? Please explain both of my doubts. Here is my simple code
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body onload="loadHandler()">
<p>Drag me!</p>
<script type="text/javascript">
function loadHandler() {
document.getElementsByTagName('p').setAttribute('draggable', true);
}
</script>
</body>
</html>
getElementsByTagName (as the name suggests) returns an array of elements. If you want the first one, take the first one.
.highlight{ color: red}
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body onload="loadHandler()">
<p>Drag me!</p>
<script type="text/javascript">
function loadHandler() {
var elem = document.getElementsByTagName('p')[0];
elem.setAttribute('draggable',true)
elem.classList.add('highlight');
}
</script>
</body>
</html>
As for why dragging is not working, perhaps the documentation might shed some light
By default, only text selections, images, and links can be dragged. For all others elements, the event ondragstart must be set for the drag and drop mechanism to work, as shown in this comprehensive example.
getElementsByTagName returns array of results, not just a single result like getElementById. Try to use getElementsByTagName('p')[0].
I know there are a lot of questions like this, but none of them seemed to solve my problem. I have this piece of code that won't run because it says Uncaught ReferenceError: run is not defined. I have tried to move the function into the body of the HTML, but to no avail. My code:
<!DOCTYPE html>
<html>
<textarea name="Text1" cols="100"rows="20" id="textbox">
</textarea>
<button onclick="run()">Export to C++</button>
<script type="text/javascript">
function run() {
var code=new Array();
var input = document.getElementById("textbox").value;
//convert things that are not subroutines here
code.push(input);
code.push("}");
...
for (var i=0;i<code.length;i++)
{
document.write(code[i]+"<br>");
}
}
</script>
</html>
The ... is irrelevant code.
Why isn't this working? Any ideas on how to fix it?
Thanks
Seems it working fine for me, but as I can see the only reason for the problem is the following.
Your page is loading piece by piece from up to down, so all the scripts are going to be included and executed one by one, all the elements are going to be shown one by one as well.
That's not this case in fact, because you are using "on click" event and there are no init actions, so it should be working, but you can try to move your <script></script> at the top (before you assign event).
<!DOCTYPE html>
<html>
<textarea name="Text1" cols="100"rows="20" id="textbox">
</textarea>
<script type="text/javascript">
you script here
</script>
<button onclick="run()">Export to C++</button>
</html>
You may also replace the whole code inside of
<script></script>
by something like alert("Hello"); to check if it's working. Possible you have the issue with internal code.
This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 6 years ago.
Ok. I need fresh eyes because I'm still on this s***d problem for one hour!
Here is my simple HTML code (testssio.html) that include javascript script:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var ssio = document.getElementById('ssio');
ssio.html = "it finally works!";
</script>
</head>
<body>
<div id="ssio"></div>
</body>
</html>
But it doesn't work! Using the debugger, I get:
Uncaught TypeError: Cannot set property 'html' of null /testssio/:6
Does anyone get it? I know it's not the correct place to look for debugging help, but I'll be crazy if I don't get it! So please, any help?
Tahnks in advance.
The reason for this is that scripts in the head load before the page is rendered. This means your content is not yet rendered and therefore not a part of document.
If you want to see this work, try moving your script below the element renders, like this:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id="ssio"></div>
<script type="text/javascript">
var ssio = document.getElementById('ssio');
ssio.innerHTML = "it finally works!";
</script>
</body>
</html>
A more standardized way of doing this is with events. Many people use jQuery but it can be done with plain js. This would mean changing your script like this:
<script type="text/javascript">
function WinLoad() {
var ssio = document.getElementById('ssio');
ssio.innerHTML = "It finally works!";
}
window.onload = WinLoad;
</script>
This way you can still leave it in the <head>.
Also, using .html is from jQuery. It is generally used as .html(content). If you want to use the plain javascript version use .innerHTML = content.
I mention jQuery so much because it is a highly used API. This quote is from their site:
jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development. jQuery is designed to change the way that you write JavaScript.
Your code is running too early before the DOM is loaded and thus document.getElementById() doesn't find the element in the document yet.
You can either move your script tag down to right before the </body> tag or you can wait for the DOM to load before running your code with either the window onload event or a DOMReady event.
There are two errors here. First, you need to put the SCRIPT tag after the element. Second, it's not .html, but .innerHTML. So here is the corrected code:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id="ssio"></div>
<script type="text/javascript">
var ssio = document.getElementById('ssio');
ssio.innerHTML = "it finally works!";
</script>
</body>
</html>
you can use something like this
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
document.onload= function(){
var ssio = document.getElementById('ssio');
ssio.html = "it finally works!";
}
</script>
</head>
<body>
<div id="ssio"></div>
is it possible to get javascript to output html where the javascript code is?
For example
<html>
<head>
<title>
</title>
</head>
<body>
<div>header</div>
<div>main
<script type="text/javascript" language="javascript">
// print some html here, maybe google
</script>
</div>
<div>footer</div>
</body>
</html>
Where the end results would look like:
<html>
<head>
<title>
</title>
</head>
<body>
<div>header</div>
<div>maingoogle</div>
</script>
</div>
<div>footer</div>
</body>
</html>
I understand that I can give the containing div and id and then get javascript to insert the anchor take like that, but I just wanted to know if it's possible to do this directly, as in write the html exactly where the javascript is?
Use document.write('YOUR_TEXT') for that
<script type="text/javascript" language="javascript">
document.write('google')
</script>
jsFiddle demo
Yes, although there are a lot of nuances to document.write, it'll output its contents immediately after the calling script element.
warning: document.write will obliterate your DOM once the dom is closed for writing. If you need to call a function asynchronously, you'll have to do DOM manipulation, otherwise document.write will rewrite everything with whatever it's supposed to output. This leads to unintentional results, which is why it's often discouraged.