Neither jQuery's .text() nor JavaScripts .innerText works? - javascript

I'm currently trying to animate some text on my website and set up a little test website to fiddle around with.
This is what my test website looks like:
<head>
<title>Test</title>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
//What I tried with jQuery
console.log("Content: " + $('p').text());
//What I tried with JavaScript
var text = document.getElementsByClassName('test').item(0);
console.log(text.innerText);
//This returns the HTMLCollection object, text[0] is undefined
var text = document.getElementsByClassName('test');
console.log(text);
</script>
</head>
<body>
<p class="test">Hello World!</p>
</body>
//What I tried with jQuery
console.log("Content: " + $('p').text());
//What I tried with JavaScript
var text = document.getElementsByClassName('test').item(0);
console.log(text.innerText);
//This returns the HTMLCollection object, text[0] is undefined
var text = document.getElementsByClassName('test');
console.log(text);
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<p class="test">Hello World!</p>
Here I'm already trying to use jQuery instead of JavaScript, because it seemed to be easier to use. But if I visit my website (locally) it only prints Content: inside the console (JavaScripts .innerText would return undefined).
If it is important: I'm using Ubuntu 19.10 to develop and test my website.

You need to wait for the page to load (DOM) before the script runs. As I see it now, your script runs before the paragraph (<p>) element is created.
You can either:
1) Make it so that the code runs once the page has loaded. (recommended) ... or
2) Move the script after the paragraph (<p>) tag.
Method 1
// jQuery
$(document).ready(function() {
console.log("Content: " + $('p').text());
});
// JavaScript
document.addEventListener("DOMContentLoaded", function(){
// Handler when the DOM is fully loaded
var text = document.getElementsByClassName('test').item(0);
console.log(text.innerText);
});
Method 2: Please refer to #Edit's answer.

Your script needs to be at the bottom of your body. Here's the result:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<head>
<title>Test</title>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
</head>
<body>
<p class="test">Hello World!</p>
<script>
//What I tried with jQuery
console.log("Content: " + $('p').text());
//What I tried with JavaScript
var text = document.getElementsByClassName('test').item(0);
console.log(text.innerText);
//This returns the HTMLCollection object, text[0] is undefined
var text = document.getElementsByClassName('test');
console.log(text);
</script>
</body>

Related

TypeError: is null (External javascript)

How do i make this code work with an external javascript file?
<!DOCTYPE html>
<html>
<body>
<h2>My First Page</h2>
<p id="demo"></p>
<script>
var elem = document.getElementById("demo");
elem.innerHTML = "Hello World!";
</script>
</body>
</html>
If i try to write this inside script.js file it will return this error:
"TypeError: elem is null"
OBS: I have no problems running this as inner HTML, just the external part is getting me.
If your script is run before the DOM has finished loading (and specifically the #demo element is not yet present), your call to getElementById will return null.
https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById
So, you need to ensure that the DOM has been loaded before querying for that element.
You can either place your script tag at the end of the document (as suggested elsewhere in this post), or utilize the DOMContentLoaded event:
window.addEventListener('DOMContentLoaded', function() {
var elem = document.getElementById("demo");
elem.innerHTML = "Hello World!";
});
Embed your javascript file before closing the body tag, so that your javascript file runs after the page loads. Otherwise your code will run before the demo element added to the page:
<script src="external.js"></script>
And use only inner part of the inline script in the external file:
var elem = document.getElementById("demo");
elem.innerHTML = "Hello World!";
Import your external javascript file at the end of the DOM. When you call your javascript file at the header, your script searches element before being loaded. That's why it gives error. Try this now!
<!DOCTYPE html>
<html>
<body>
<h2>My First Page</h2>
<p id="demo"></p>
<script src="script.js"></script>
</body>
</html>

My variable can't hold "document.querySelector(".content") " , it returns null [duplicate]

This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 4 years ago.
This is my HTML :
<html>
<head>
<script src="domManipulating.js"></script>
</head>
// The DOM
<body>
<h1>
THE TITLE OF YOUR WEBPAGE
</h1>
<div id="container">
<div class="content">
This is the glorious text-content!
</div>
</div>
</body>
</html>
And this is my JS
var content = document.querySelector(".content");
var paragraph = document.createElement("p");
paragraph.textContent = " Hey I'm red";
content.appendChild(paragraph);
When I use the console to test my code a error appears :
Uncaught TypeError: Cannot read property 'appendChild' of null
From my understanding the variable content can't hold document.querySelector(".content")
When I write document.querySelector(".content")in the console it actually works but when I use var paragraph = document.createElement("p");the variable turns into a null.
Why is that happening?
The issue seems to be with <script src="domManipulating.js"></script> loading before DOM is ready. In that case document.querySelector will not able to find the element from the DOM
One alternative is to load the script just before closing body tag
<body>
//html tags
<script src="domManipulating.js"></script>
</body>
var content = document.querySelector(".content");
var paragraph = document.createElement("p");
paragraph.textContent = " Hey I'm red";
content.appendChild(paragraph);
<h1>
THE TITLE OF YOUR WEBPAGE
</h1>
<div id="container">
<div class="content">
This is the glorious text-content!
</div>
</div>
Look at the location of your script tag in your HTML: it's above the body. At the time the script runs, the body (and all of its content, including .content) has not been created yet.
Either wrap your whole script in a function that runs once the document is loaded:
document.addEventListener('DOMContentLoaded', () => {
var content = document.querySelector('.content');
// ...
or, a better option: give your script the defer attribute, and it'll automatically run only once the document is ready to be parsed:
<head>
<script src="domManipulating.js" defer></script>
</head>

Using getElementById to duplicate content in page

I don't know javascript and I have been searching every where for this answer. I would like to duplicate content in my page. The html and content comes directly from a broker.
The result wanted is :
Click the button to change the text in this paragraph.
Click the button to change the text in this paragraph.
My HTML is:
<!DOCTYPE html>
<html>
<body>
<p id="demo">Click the button to change the text in this paragraph.</p>
<script language="javascript" type="text/javascript">
var elem = document.getElementById('demo').setAttribute('id', 'nextstep');
document.write(elem);
</script>
</body>
</html>
What I am getting is:
Click the button to change the text in this paragraph.
undefined
Can somebody help point me in the right direction? Thanks in advance!
I don't believe you want to be using document.write. I think this is what you're after:
<script language="javascript" type="text/javascript">
// this gets the element
var elem = document.getElementById('demo');
// this copies the entire element, including the id
var newElem = elem.cloneNode(true);
// this sets a new id
newElem.setAttribute('id', 'nextstep');
// generic way to make sure you insert properly
var before = elem.nextSibling;
// there's no insertAfter, only insertBefore, which is why we found the before
elem.parentNode.insertBefore(newElem, before);
</script>
FIDDLE
You need to grab the innerHTML and set it:
var elem = document.getElementById('demo').innerHTML;
document.write(elem);
Beware though, document.write is going to overwrite everything..
If u need to get this
<p id="demo">Click the button to change the text in this paragraph.</p>
<p id="nextstep">Click the button to change the text in this paragraph.</p>
try
<!DOCTYPE html>
<html>
<body>
<p id="demo">Click the button to change the text in this paragraph.</p>
<script language="javascript" type="text/javascript">
var elem = document.getElementById('demo');
var newElem = document.createElement('div');
newElem.innerHTML = "<p id='nextstep'>" + elem.innerHTML + "</p>";
document.write(newElem.innerHTML);
</script>
</body>
</html>
You are setting elem to the return value of setAttribute, which is undefined as it returns nothing.
Change the code to:
var elem = document.getElementById('demo');
elem.setAttribute('id', 'nextstep');
document.write(elem.innerHTML);
Example - http://jsfiddle.net/P8EcL/
This still does not end up with exactly what you want as it is copy of the content of the p tag rather than the tag itself.
Scott Mermelstein's answer is what you want.
var elem = document.getElementById('demo').innerHTML;
document.write(elem);
I'm not sure why you're trying to set a new id on the original div and expect it to return the HTML, but it's not going to work ;)

How can I save the contents of a textarea as a variable using javascript in an external document?

I have tried, as many have suggested, saving a variable as the .value or .innerHTML of an ID, found by using document.getElementById. Here is all of my HTML:
<html>
<head>
<title>write</title>
<script type="text/javascript" src="g.js"></script>
<link rel="stylesheet" type="text/css" href="g.css" />
</head>
<body>
<div id="box">
<textarea id="txt" placeholder="placeholder. type here.">text text</textarea>
</div>
</body>
</html>
and here is my javascript, currently meant to fire an alert that contains the text in the text area – right now that would be, text text:
function run(){
var txt = document.getElementById('txt');
alert(txt);}
run()
Right now, loading the page fires an alert with the text Null and adding .value after getElementById('txt') results in no alert. Many thanks in advance.
The problem is that your javascript is executing before the DOM is constructed. When you load the JavaScript file in the <head> of the document, it is executed immediately, before the <textarea> tag has been created.
Try moving your script block below the textarea, just before the </body> tag.
Here's an example: fiddle
After the DOM is constructed you can use getElementById just as have and can access the contents of the textarea with the value attribute. All of this is in the fiddle above.
Alternatively, you can wrap your run() method call with a library that provides an event when the DOM becomes ready. jQuery's example would be:
$(function () {
// code you want to execute when the DOM is ready.
run();
});
function run() {
var txt = document.getElementById("txt").value;
alert(txt);
}
$(document).ready(function(){
run();
});
check this jsfiddle link
You are not getting textarea value because your javscript function is getting executed before there's value in DOM
or using javascript
function run(){
var txt = document.getElementById("txt").value;
alert(txt);
}
window.onload = run();
More about window.onload
The javascript below works in firefox. In fact, if you click the answer button for this question, you can try it out in firebug on this very page...
var textArea = document.getElementById("wmd-input"); // #wmd-input is the text input where your answer goes...
alert( textArea.value );
Make sure you enter some text first, of course.
While you're at it, you should give jQuery a try:
alert( $("#wmd-input").val() );
Or better yet,
console.log($("#wmd-input").val());
Hope that helps.

Manipulating DOM with (framework-less) javascript

Ok, I haven't been using JavaScript without JQuery for quite some time now... But, as coding goes, I have to do without it's power for a project where I can't be sure that JQuery is provided.
The thing I'm trying to do would be the following using JQuery:
$(document).ready(function() {
$('#myDiv').append('<ul><li>a</li><li>b</li></ul>');
});
Now to the non-jquery thing, this is what I have and I really can't understand why it isn't working:
<html>
<head>
<script type="text/javascript">
function load() {
var s = '<ul><li>a</li><li>b</li></ul>';
var element = document.getElementById("myDiv");
element.innerHtml += s;
}
</script>
</head>
<body onload="load()">
<div id="myDiv"></div>
</body>
</html>
Thing is, nothing happens (the function gets called though). Could it be that the DOM isn't ready when load() is called?. I vaguely remember this code working in the firefox 2.x IE7 era ...
What would be the (a) right solution?
It's innerHTML not innerHtml. Notice the upper case HTML. Change that and it should work fine! Here's a working example.
By using innerHtml you are simply creating a new property on the element object and giving it the value of s.
<html>
<head>
<script type="text/javascript">
function load() {
var s = '<ul><li>a</li><li>b</li></ul>';
var element = document.getElementById("myDiv");
element.innerHTML += s;
}
</script>
</head>
<body onload="load()">
<div id="myDiv"></div>
</body>
</html>
JS is case sensitive
I think you want element.innerHTML += s;.

Categories

Resources