Javascript innerHTML not changing div contents [duplicate] - javascript

This question already has answers here:
What do querySelectorAll and getElementsBy* methods return?
(12 answers)
Closed 4 years ago.
I am trying to change the text displayed by a div from 'hello' to 'hey' on click using innerHTML. I know my function is executed and the innerHTML is changed because I get an alert on click displaying 'hey', but on my webpage and in inspector the 'text' element's contents remain as 'hello'.
What is going on here?
code:
<html>
<head>
<script type="text/javascript">
function changehtml() {
var text = document.getElementsByClassName('text');
text.innerHTML = 'hey';
alert(text.innerHTML)
}
</script>
</head>
<body>
<div class='text' onclick='changehtml()'>
hello
</div>
</body>
</html>

Get elements by class returns an array of elements if you just want to change the one div give it and id and getElementById.
If you want to change multiple divs with that class the second snippet loops through the divs with that class and changes all of their texts.
function changehtml() {
var text = document.getElementById('x');
text.innerHTML = 'hey';
alert(text.innerHTML)
}
<html>
<head>
</head>
<body>
<div id="x" class='text' onclick='changehtml()'>
hello
</div>
</body>
</html>
function changehtml() {
var text = document.getElementsByClassName('text');
for (let i = 0; i < text.length; i++) {
text[i].innerHTML = 'hey';
}
}
<html>
<head>
</head>
<body>
<div class='text' onclick='changehtml()'>
hello
</div>
</body>
</html>

document.getElementsByClassName('text') gives you collection of nodes. So, you;ll have to loop through them to get each node. Or for this example you can use
document.getElementsByClassName('text')[0];
Or
document.querySelector('.text')
This will give you the first node with class name of text.
And make it your habit to check your console for errors, you'll probably be getting one

Related

How can I use a parameter to change HTML text?

I'm using an API, and am trying to access the value of product.shoeName to change text on my HTML page. This is my code:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript"
src="shoepoo.js">
</script>
</head>
<body>
<div>
<p id="text" style="color:purple;
font-weight:bold;font-size:20px;">
</p>
<script type="text/javascript"> shoeName(); </script>
</div>
</body>
</html>
const SneaksAPI = require('sneaks-api');
const sneaks = new SneaksAPI();
//getProducts(keyword, limit, callback) takes in a keyword and limit and returns a product array
function shoeName(){
sneaks.getProducts("Jumbo Blazer", 1, function(err, products){
products.forEach(
function names (product) {
document.getElementById("text").innerHTML = product.shoeName;
})
});
};
Basically, I want product.shoeName to be shown as text, but nothing is showing up. How can I fix this? I understand it's a local function which is probably stopping the data from being shown (or something like that), but how can I work around this?
Made below changes in shoepoo.js
products.forEach((product)=> {
document.getElementById("text").innerHTML = product.shoeName;
});
But you need to create dynamic HTML components if there is multiple data in products. Otherwise, it set the last shoeName in the paragraph component.

Why the value of document.getElementById("greeting") is 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 6 years ago.
<!-- This is the HTML element -->
<h1 id="greeting"></h1>
JS
var currentUser = localStorage.getItem("currentUser");
document.getElementById("greeting").innerHTML = "Hi " + currentUser;
Here is what happens when inspect the page, it says:
Uncaught TypeError: Cannot set property 'innerHTML' of null(…)
This would be the entire code file.
//mypublicwebsites.tk/artem/databases/a/load_home.js
//This isn't the complete code because I cannot use 'localStorage' in a code snippet
//excluding unneeded code
var isSignedIn = true;
//The current user, lets just say that is me
var currentUser = "Sean";
if(isSignedIn) {
load();
} else {
window.location.replace("index.html");
}
function logOut () {
localStorage.setItem("isSignedIn","false");
localStorage.setItem("currentUser", "none");
window.location.replace("index.html");
}
function load() {
document.querySelector(".greeting").innerHTML = "Hi " + currentUser + "!";
}
<!DOCTYPE html>
<html>
<head>
<title>Artem Inc. | Database A -> Home</title>
<script src="mypublicwebsite.tk/artem/databases/a/load_home.js"></script>
</head>
<body>
<div id="menu">
<button onclick="logOut()">Log Out</button>
</div>
<h1 class="greeting"></h1>
</body>
</html>
It does seem to work in the snippet but not in the browser.
Fine, I'll post the answer I found. You need to wait for the webpage to load and then execute the script, so I put the script right before the closing body tag.
After checking your source over at Github i notice that there is no element of id greeting at https://github.com/codecademy123/codecademy123.github.io/blob/master/artem/databases/a/home.html :
<!DOCTYPE html>
<html>
<head>
<title>Artem Inc. | Database A -> Home</title>
<script src="load_home.js"></script>
</head>
<body>
<div id="menu">
<button onclick="logOut()">Log Out</button>
</div>
<h1 class="greeting"></h1>
</body>
</html>
No id but there is a class with the name greeting.
Here's an updated and simplified fiddle:
https://jsfiddle.net/tommiehansen/ndd0c7rh/2/
Basically we just use document.querySelector('.greeting') instead of document.getElementById('greeting') since the id greeting will always return undefined if it does not exist.
If you want to still use an id simply change the source code for home.html from <h1 class="greeting"></h1> to <h1 id="greeting"></h1>. The important part here is to query the DOM after what you've set the class or id to be. Because if you do not match these it will always return as undefined since your javascript will not be able to find the selector.

Javascript display all (elements, tags) from method elementsbyTagName

Im learning JavaScript and i have problem with DOM methods.
HTML
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="DOM_Ponovno.js"></script>
</head>
<body>
<div>
<p id="demo" >
this is the first paragraph</p>
<p> boooooooooooommmmmmmmmmmm</p>
<p> third paragraph </p>
<button onclick="changeText()">click me</button>
</div>
</body>
function changeText() {
var tmpTag = document.getElementsByTagName("p");
for(var i = 0;i< tmpTag.length;i++) {
document.write(tmpTag[i].textContent);
}
}
If i follow the tutorial its ok, but i wanted to display all elements by tag name p. I want to display all paragraphs stored in tmpTag.
Someone please explain:
How can ( why cant) display all elements with tag name p ?
How can (why cant) display 3x p tag from variable tmpTag ?
Tried to change to Array with prototype.slice.call method but no success.
You know like Java stuff loop through display/change at index etc..
Thank you :)
Hi and thanx for fast answers.. Sory about the function name it was for testing... I just want to display all elements by tag name p. This code displays only first element and i counter in for loop stops at 1. Why cant i get other 2 paragraph elements ?
Im using document.write like system.out.print in Java to see whats in array. I know if i wanna change i need innerHTML.
If you are wanting to update each paragraph, do not use document write. Try the following:
function changeText() {
var tmpTag = document.getElementsByTagName("p");
for(var i = 0;i< tmpTag.length;i++) {
tmpTag[i].innerHTML = "Your new updated text to change it to for tag index " + i + "...";
}
}
As #Juhana mentioned, the moment you start your loop you overwrite the document using document.write, so all your p tags get removed from the document and replaced by the text in the first paragraph and then your function fails, as the now-empty objects don't have any textContent property. You could concatenate all the contents and write it once:
function changeText() {
var tmpTag = document.getElementsByTagName("p");
var print = '';
for(var i = 0;i< tmpTag.length;i++) {
print += tmpTag[i].textContent;
}
document.write(print)
}
But actually, just don't use document.write - SO snippets don't even allow it anymore! Here a way with a div as output:
var output = document.getElementById('output');
function changeText() {
var tmpTag = document.getElementsByTagName("p");
for(var i = 0;i< tmpTag.length;i++) {
output.textContent += tmpTag[i].textContent;
}
}
<div>
<p id="demo" >this is the first paragraph</p>
<p> boooooooooooommmmmmmmmmmm</p>
<p> third paragraph </p>
<button onclick="changeText()">click me</button>
</div>
<div id="output"></div>
I'm not sure what you're trying to do but you can add another div for result with id='result' and append result you want to it, check following example.
Hope this will help.
function changeText() {
var tmpTag = document.getElementsByTagName("p");
var result = document.getElementById('result');
for(var i = 0;i< tmpTag.length;i++) {
result.innerHTML += tmpTag[i].textContent+'<br>';
}
}
<div>
<p id="demo" >
this is the first paragraph</p>
<p> boooooooooooommmmmmmmmmmm</p>
<p> third paragraph </p>
<button onclick="changeText()">click me</button>
<br>
<div id="result" ></div>
</div>

Iframe content to store in textarea [duplicate]

This question already has answers here:
How to change the Content of a <textarea> with JavaScript
(6 answers)
Closed 8 years ago.
Is there a way to retrieve the content from iframe and store it in textarea using pure JavaScript??
I have retireve the content from iframe using following code:
function getIframeContent(){
var frameObj = document.getElementById(frameId);
var frameContent = frameObj.contentWindow.document.body.innerHTML;
alert("frame content : "+frameContent);
}
Now how to store it in the textarea??
You can display the content of your iFrame inside your TextArea like so
document.getElementById('YourTextArea').innerHTML = frameContent;
or using the Value attribute:
document.getElementById('YourTextArea').value = frameContent;
I have done a quick demo for you using the first method.
This returns a string with any html tag in it. So for example if your iframe contains a list, the method returns an html list.
Here's the code:
<body>
<div id="frameId">
<ul>
<li id="item1">Coffee</li>
<li id="item2">Tea</li>
</ul>
</div>
<p>Click the button get the HTML content of the iframe.</p>
<textarea id="demo"></textarea><br/>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
var frameContent = document.getElementById("frameId").innerHTML;
document.getElementById("demo").innerHTML = frameContent;
}
</script>
</body>

Can the mouseover event be used on any element, or only on images?

<html >
<head>
<title>JavaScript Example</title>
<script type="text/javascript">
function greet {
var greet = document.getElementById("greeting");
greet.value="this is dynamic";
</script>
</head>
<body>
<p onmouseover="greet()"> Hello! Welcome to My Page </p>
</html>
What is the problem in this code?
Firstly, you haven't closed your greet function (missing the closing } character). Secondly, you're missing the parentheses after the name of the function:
function greet() {
//Function body
}
Secondly, you're using getElementById to try and obtain a reference to the p element, but the p element doesn't have an id.
Thirdly, the greet variable will contain a reference to a p element, which doesn't have a value property (like, for example, input elements do). You may have meant innerHTML if you are trying to change the contents of the element.
Finally, you haven't closed your <body> element. Edit (see comments) - This isn't a problem, but personally I prefer closing it for consistency.
You could pass a reference to the element into the function when it's called, to save you having to get it by id:
<p onmouseover="greet(this);">Example</p>
And JavaScript:
function greet(elem) {
elem.innerHTML = "Something new";
}
the p element should have an ID of greet, as in:
<p onmouseover="greet()" id="greeting"> Hello! Welcome to My Page </p>
, so that when you select the element's ID at:
document.getElementById("greeting");
the document can find the tag you are trying to select from the HTML document.
Additionally, instead of editing the node's "value" attribute, I think you need to use the "innerHTML" instead. So that gives:
<html >
<head>
<title>JavaScript Example</title>
<script type="text/javascript">
function greet {
var greet = document.getElementById("greeting");
greet.innerHTML="this is dynamic";
}
</script>
</head>
</body>
<p onmouseover="greet()" id="greeting"> Hello! Welcome to My Page </p>
</html>
I am not exactly familiar with JavaScript, but I believe that should work.
You can try:
greet = function(elem) {
elem.innerHTML = "Something new";
}
or
greet = function() {
var greet = document.getElementById("greeting");
greet.innerHTML="this is dynamic";
}
Along with the other tips of course(like id attribute for the relevant <p> element and well-forming your HTML).

Categories