which property should I choose to set "text" HTML element? [duplicate] - javascript

This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 1 year ago.
I would like to change text in P or other tag in HTML with Java Script
I tried to many different ways.
However, any of those didn't work well.
Console says.
Uncaught TypeError: Cannot set property 'textContent' of null
<script>
//1 document.getElementById("stackoverflow").textContent="newtext";
//2 document.getElementById("stackoverflow").value ="newtext";
//3 document.getElementById("stackoverflow").innerHTML ="newtext";
<script>
<div class="row">
<p id="stackoverflow">I wanna change this text</p>
</div>

Two changes
move your script after element is loaded
remove id from markup
below code works
document.getElementById("stackoverflow").textContent="newtext";
<p id="stackoverflow">I wanna change this text</p>

Check your id there is no space in between.
id is stackoverflow and your giving document.getElementById("stack overflow")

That is completly normal as long as you have two id attributes on the p tag only the first one will be consider.
let p = document.getElementById("stackoverflow");
console.log(p);
<p id id="stackoverflow">This is a sample paragraph</p>
But when you remove the first id it should work as expected
let p = document.getElementById("stackoverflow")
console.log(p);
<p id="stackoverflow">This is a sample paragraph</p>
let p = document.querySelector("p");
console.log(p.id);
<p id id="stackoverflow">This is a sample paragraph</p>
As you can see the idattribute is empty

there are 2 ways ,
1 - if you are doing onload event , u can wrap this within your body tag and call your function
2 - if its onlclick event , call this function onclick eventremove comment on button and onload = "ChangeEvent()"
<!DOCTYPE html>
<html>
<script>
function ChangeEvent() {
document.getElementById("stackoverflow").textContent = "HI";
}
</script>
<body onload="ChangeEvent()">
<p id="stackoverflow">Change</p>
<!-- <button onclick="ChangeEvent()">Clicked</button> -->
</body>
</html>

Place always your <script> tag right before the closing </body> tag
Close properly the </script> tag
<head>
<!-- HEAD stuff goes here. link, meta, title etc -->
</head>
<body>
<div class="row">
<p id="stackoverflow">I wanna change this text</p>
</div>
<!--
SCRIPTs go here before the closing </body>
-->
<script>
document.getElementById("stackoverflow").textContent="newtext";
</script>
</body>
Additional read on parser blocking versus asynchronous javascript

Related

2 separate scripts in HTML/JS are interfering with each other [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I am learning HTML/JS and I am having trouble with this script. I am practicing making buttons that preform actions but when I got to the the part of where clicking text doing actions like changing innerHTML. I have tried moving the script to a different location on the page but with no luck anytime I press the element that changes text it makes the other script do the action but not the one I clicked. I am referring to when I use
<h1>Click to change text color</h1>
<p id="siaz" onclick="myFuntion()">Click me to make my text change color!</p>
<script>
function myFuntion() {
document.getElementById("siaz").style.color='red';
}
</script>
</body>
I am only having trouble with both myFuntion() scripts. Please help. See issue for yourself by loading it in an editor.
<!DOCTYPE>
<html>
<center><font face = "Canela" fontSize = "35px" style = "color: darkblue"><h1>Just practice</h1></font></center>
<body>
<font face = "Didot"><h1>Change text</h1></font>
<p id="mill">This text will change</p>
<button type = "button" onclick = 'document.getElementById("mill").innerHTML="Changed!"'>Click to change!</button>
</body>
<body>
<font face = "Papyrus" ><h1>This will make text reappear</h1></font>
<p id="disa" style = "display:none">This text will be reappear</p>
<button type = "button" onclick = "document.getElementById('disa').style.display='block'">Click to reappear</button>
</body>
<body>
<font face = "Verdana"><h1>This will make text disappear</h1></font>
<p id="deps">This text will go away when you click that button</p>
<button type = "button" onclick = "document.getElementById('deps').style.display='none'">Click to make this text go away!</button>
</body>
<body>
<h1>This will Change the font size</h1>
<p id="clas">This should become bigger</p>
<button type = "button" onclick = "document.getElementById('clas').style.fontSize='45px'">Click to make the size bigger</button>
</body>
<body>
<h1>Click to change text color</h1>
<p id="siaz" onclick="myFuntion()">Click me to make my text change color!</p>
<script>
function myFuntion() {
document.getElementById("siaz").style.color='red';
}
</script>
</body>
<body>
<h1>Clicking the text will change the text</h1>
<p id="home" onclick = "myFuntion()">Click me, I dare you</p>
<script>
function myFuntion() {
document.getElementById('home').innerHTML="Go away"
}
</script>
</body>
</html>
You should have only one script, but you can put in as many functions as you want. You can have a changeColor function, a changeFont function (you can name then whatever you want but should have an appropriate description so it's easier to read it).
<p id="siaz" onclick="changeColor()">Click me to make my text change color!</p>
<p id="home" onclick="changeText()">Click me, I dare you</p>
<script>
function changeColor() {
document.getElementById("siaz").style.color='red';
}
function changeText() {
document.getElementById('home').innerHTML="Go away";
}
</script>
Irrespective of what you are trying to achieve, that's not the good practice to follow.
Even if you are learning
Learn the right practices at the start itself. So, a few changes needed
There can only be 1 <body> tag
Follow proper naming conventions - Method name should be a verb e.g.: changeFontColor(), changeFontSize(), etc.
Seperate html templates, styling and scripts - Use css instead of elemtents like font. No inline css or internal javascript. Keep it in separate file or in a single separate section.
Code should be properly indeneted
As you are new to this, I have shared a template for designing html pages which you could refer to start with
<!DOCTYPE>
<html>
<head>
<style>
<!-- All css styles goes here -->
</style>
</head>
<body>
<!-- All html code goes here -->
<script>
<!--All scripts goes here -->
</script>
</body>
</html>
Solution: If you could just change the
myFunction()
which changes the color to
myFunction1 or anything other than "myFunction"
at both the places (the function definition where you change the color and at the place where you are calling it, the onclick for color change) then it will start working.
Reason: As Keith said in the comments, in the global scope, we shall have unique function names, otherwise, the last one defined takes the precedence.
Best,
Sumit

how to get all the data of html body tags to ending body tags in javascript?

same type of question: Get all elements in the body tag using pure javascript
I have a very large HTML, CSS and javascript code in the HTML file
so, I want to show them in short cut ways
suppose;
<body>
<div class="w3-red">
<h1> this is <h1>
</div>
<div class="w3-red">
<h1> this is <h1>
</div>
<div class="w3-red">
<h1> this is <h1>
</div>
</body>
<p id="demo"></p>
I want to capture the data inside the HTML body tag in javascript and assign to the variable
The assign to variable result is same as above code
Here is the javascript code
<script>
var myCollection = document.body.getElementsByTagName("*");
document.getElementById("demo").innerHTML =
"The innerHTML of the second paragraph is: " +
myCollection[2].innerHTML;
</script>
I guess this could help you, if you take a look into :
$("body").get(); //Returns a body Object
$("body").get()[0].children //Returns all html tags directly below the body tag

Can't get Javascript to display variable to html document [duplicate]

This question already has answers here:
Difference between ".innerHTML" and ".value" in JS
(4 answers)
Closed 4 years ago.
I know there is something wrong with my code and seeing as this is my hello world project I am very confused. I have read other posts but nothing will work. Can somebody make this work for me??.
The HTML
<html>
<head>
<link rel="stylesheet" href="game.css">
</head>
<body onload="startgame()">
<div id=content>
<center>
<div id=pricediv>
<p id=price></p>
</div>
<div id=buysell>
<button class=buy>Buy</button>
<button class=sell>Sell</button>
<button onclick="startgame()">Start</button>
</div>
</center>
</div>
</body>
The JavaScript
var paused = "false";
function startgame() {
while (paused === false) {
var price = Math.round(Math.random());
document.getElementById("price").innerHTML = price;
}
}
<p> tags don't have value.
Use innerHTML instead.
Also "price" will display word price instead of variable, so drop the quotes:
document.getElementById("price").innerHTML= price
Use .innerHTML instead of .value.
.value is used to set the value of an input element, ie. <input> or <textarea>.
.innerHTMl is used to set the string value in between a html tag, ie. <h1>, <p> or <div>.

Cannot get the hidden tag value

Here is my code:
<html>
<head>
<script type="text/javascript">
var x= document.getElementById("2").value;
document.getElementById("1").innerHtml = x;
</script>
</head>
<body>
<p hidden="hidden" id="2">This paragraph should be hidden.</p>
<p>This is a visible paragraph.</p>
<p><b>Note:</b> The hidden attribute is not supported in IE.</p>
<p id="1"></p>
</body>
</html>
in this code i have a hidden tag as you can see. I want that the javascript code read text value of the p tag with an id 2 and then print the same value to other <p> tag wiht id="1". But this is not working. Earlier i even tried to use nodeValue but also this is not working and when i checked out in google developer tool then it was showing an error as following:
Cannot read property 'value/nodeValue' of null
please note:
after a quick experiment i noted that after adding a event handler <body onload="y();>" there was no error but there was no expected result!
please help!
hidden is an input element type, not a p attribute:
<input type="hidden" id="2" value="This input should be hidden." />
There are three problems:
there is no innerHtml, innerHTML is the correct syntax.
the hidden "p" does not have a value, it is not an input field. use innerHTML for accessing it.
your javascript code runs before the browser knows about paragraps, so they don't exist when you want them to be accessed. put javascript after the paragraphs or run the code after the page is loaded.
this should work:
<html>
<head>
</head>
<body>
<p hidden="hidden" id="2">This paragraph should be hidden.</p>
<p>This is a visible paragraph.</p>
<p><b>Note:</b> The hidden attribute is not supported in IE.</p>
<p id="1"></p>
<script type="text/javascript">
var x= document.getElementById("2").innerHTML;
document.getElementById("1").innerHTML = x;
</script>
</body>
</html>
Don't use numbers for ID.
Try something like <p id="hello"></p>
I think you need to change your tag to then you can set a CSS class with .hidden { display:none; }.
Wrap your Javascript in a function and call it when you need to or go back to your
Also as Maaz said, try not to use numbers in your ID's.
var hiddenValue = document.getElementById('2').innerHTML;
document.getElementById('1').innerHTML = hiddenValue;
The problem with this (and if you try and style it also) is that classes and ID's should not start with (or include) numbers.
Rename your ID's to one and two and then update your javascript accordingly.
e.g
<p id="one">Some stuff</p>
Also hidden cannot be used with a p element as it's for inputs only.
You're better off using display:none; in CSS.
If you NEED to access it via css as a number, you can use
[id='1']{
/*code*/
}
but your javascript still wont work.
As James has pointed out, using numbers for ID's is perfectly valid in HTML5.

Add button after script tag

I have a javascript that I want my users to be able to put on their sites. In this javascript, I want to generate a simple button, that is located exactly where the javascript has been pasted into the site. How can I do this? It would be simple if I could give my <script> tag an id and then just getting the element with the specific ID and appending after it, but I can't.
For example if I have something like this:
<body>
<p>test para</p>
<p>test para</p><p>test para</p><p>test para</p>
<p>test para</p>
<div>test div</div>
<script src="embed.js" type="text/javascript"></script>
<div>last div</div>
</body>
I want my button to be placed right between test div and last div (before or after the script tag, it doesn't matter). Can I do this?
Could you just use after -
$("div:contains('test div')").after('<input type="button"/>');
This would obviously be better if you could give the 'div' an id or a class rather than finding it by the text it contains.
jQuery can find a script tag using -
$("script[src='embed.js']").after('<input type="button"/>')
Demo - http://jsfiddle.net/7GPx7/1
embedding JavaScript something you may want to consider is your visitors may not have jQuery enabled on their sites, so you could bloat the call by loading jQuery or construct your requirement in pure JavaScript.
The embed snippet for your visitors
<script id="eduard_luca" src="http://cdn.example.com/embed.js" type="text/javascript"></script>
embed.js
var element = document.createElement('a');
element.setAttribute('href','http://google.com');
element.innerHTML = 'Click Me';
document.getElementById("eduard_luca").appendChild(element);
I Hope this help you with your project.

Categories