Javascript: Why doesn't getElementById(theID) work with innerHTML? - javascript

Why doesn't getElementById(theID) work with innerHTML?
Works:
<p id="demo" onclick="myFunction()">Click me to change my HTML content (innerHTML).</p>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed!";
}
</script>
Doesn't work:
<p id="demo" onclick="myFunction()">Click me to change my HTML content (innerHTML).</p>
<script>
function myFunction() {
document.getElementById(theID).innerHTML = "Paragraph changed!";
}
</script>
JSFIDDLE
getElementById(theID) works with style.display:
<style>
h2 {
display: inline;
}
.openclose {
cursor: pointer; /* or: hand; */
margin-left: 1em;
}
.image {
display: none;
}
</style>
<script>
function openClose(theID) {
if (document.getElementById(theID).style.display == "initial") {
document.getElementById(theID).style.display = "none"
document.getElementsByTagName("span")[0].innerHTML = "[+]"
} else {
document.getElementById(theID).style.display = "initial"
document.getElementsByTagName("span")[0].innerHTML = "[–]"
}
}</script>
<h2>Heading - 1st</h2><span class="openclose" onClick="openClose('a1')">[+]</span>
<br /><br /><img id="a1" class="image" src="data:image/png;base64,
iVBORw0KGgoAAAANSUhEUgAAAEAAAABAAgMAAADXB5lNAAAAC
VBMVEX///8AAAD/AADAyZ2wAAAAg0lEQVQ4y73QsQnEMBBE0bFByeVqQlW4BAWa5KpxKZcciK3SA
1IBg4z9E7EvWMTixRJVvQUaShf6kBtQ+ng9SOz4RPxQWF04YraZkHjsWqA158a6CBW7ZsmJ9CTEg
LDhGzF+GvG3gbN1IJsOrQNn0gMJBkCzB8iYNdjQ5usDOMMCvNYFYQmUU1ZqYuIAAAAASUVORK5CY
II=">
<br /><br />
<h2>Heading - 2nd</h2><span class="openclose" onClick="openClose('a2')">[+]</span>
<img id="a2" class="image" src="http://cdn.sstatic.net/stackoverflow/img/favicon.ico">
As tested here.
Additionally is it possible to ambiguate getElementsByTagName("span")[0] to something like getElementsByTagName(theTagName)[theIndexNumber]?

You should pass theID as a parameters.
<p id="demo" onclick="myFunction('demo')">Click me to change my HTML content (innerHTML).</p>
<script>
function myFunction(theID) {
document.getElementById(theID).innerHTML = "Paragraph changed!";
}
</script>
http://jsfiddle.net/c5ae2uwe/

Because you're not using the correct ID ('demo') and instead using a variable which doesn't appear to be set anywhere in your example. Another tip, since you're calling onClick on the p element you can reference it with 'this' instead of doing another document lookup.
this.innerHTML = "Paragraph changed";

Your myFunction is expecting the ID of the element whose content to be changed as a parameter, but you are not passing it
<p id="demo" onclick="myFunction('demo')">Click me to change my HTML content (innerHTML).</p>
<script>
function myFunction(theID) {
document.getElementById(theID).innerHTML = "Paragraph changed!";
}
</script>
Demo: Fiddle

See the below code. the variable "theID" is passed a value of the id of tag. Now this variable is passed to the getElementById() function.
This is just for explanation purpose and this is considered as bad coding.
<p id="demo" onclick="myFunction()">Click me to change my HTML content (innerHTML).</p>
<script>
function myFunction() {
var theID = "demo";
document.getElementById(theID).innerHTML = "Paragraph changed!";
}
</script>
To answer your other question:
Additionally is it possible to ambiguate
getElementsByTagName("span")[0] to something like
getElementsByTagName(theTagName)[theIndexNumber]?
getElementsByTagName() returns an array of elements. Hence you could use something like:
getElementsByTagName(theTagName)[theIndexNumber]
But ensure, the function call has returned atleast one element and the variables "theTagName" and "theIndexNumber" has right values.

Related

print text when button is pressed

A fellow noob here. I was wondering how can I make this button print something when pressed, I tried the document.write() but it prints it on a new clear page, I want it to be just like the image I attached.
Any ideas :D
<button onclick = "myVidPlayer.requestPictureInPicture()" " Id="togglePipButton"
>START</button>
If you are refering to print as write to DOM element or console use below code:
const someData = 'the_Data_You_Want_To_Print'
document.getElementById('printButton').onclick = function() {
//print in DOM element
document.getElementById('printHere').innerHTML = someData;
//print on console
console.log(someData)
};
#printHere {
position: absolute;
top: 15%;
left: 6%;
font-size: 5vw;
}
<button id="printButton">Click Me To Print</button>
<p id="printHere"></p>
You could use an alert window.
alert("Hello! I am an alert box!!");
or something like this:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Alert</h2>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
alert("I am an alert box!");
}
</script>
</body>
</html>

Why won't my button do the function when I click it it. It should toggle the text

Function
function myFunction() {
var x = document.getElementById("myDIV");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
<button onclick="myFunction()">Try it</button>
<div id="myDIV">
This is my DIV element.
</div>
I found this code on W3Schools and replaced "myDIV" with "h3" so I can change the text in my header
<div class="speech-buble-top"><h3 id="h3"> Happy Birthday Tiffany!</h3></div>
there are no script tags add the javascript tags.
<script type="text/javascript"> your code </script>
The issue stems from you declaring the function using the function keyword. Usually this is fine, but I find that it's easier to work with javascript functions called by HTML as functions that have been assigned to a variable. If you use ES6 arrow syntax, you'll both be using the latest standards and binding the function to a variable. Try rewriting the function code like so:
<script>
myFunction = () => {
var x = document.getElementById("myDIV");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
</script>
<button onclick="myFunction()">Try it</button>
<div id="myDIV" style="display: none">
<h3 id="h3"> Happy Birthday Tiffany!</h3>
</div>
Your JS function must be declared before your button. And must be enclosed in <script> </script> tags
You could use addEventListner() insted of inline HTML onclick(). Try this:
var x = document.getElementById("myDIV");
document.getElementById("myBtn").addEventListener('click', function() {
if (x.style.display == "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
});
#myDIV {
border: 1px solid black;
padding: 3px;
}
<button type="button" id="myBtn">Show</button>
<div id="myDIV" style="display: none;">Show the content</div>
Notice that x.style.display detect the inline style HTML attribute. Becouse of that, if you use a separate css file to styling the div, you'll need twice click for the first time...
If you are trying to inline your code within the webpage then yes you will need to make sure you classify what type of code you are using. <style></style> is for CSS and <script></script> is for Javascript.
It seems like you are trying to perform a simple hide/show script. One thing that you should work on is efficiency of your code. The chunky code in your question can be shortened to this:
function toggleHide() {
var element = document.getElementById("myDIV");
element.classList.toggle("hide");
}
.hide {
display: none;
}
<button onclick="toggleHide()">Try it</button>
<div id="myDIV">This is a DIV element.</div>
Here is what it looks like inline:
<style>
.hide {
display: none;
}
</style>
<button onclick="myFunction()">Try it</button>
<div id="myDIV">This is a DIV element.</div>
<script>
function myFunction() {
var element = document.getElementById("myDIV");
element.classList.toggle("hide");
}
</script>

Very Basic Javascript: Change HTML ID

I can't seem to get this to work at: https://jsfiddle.net/xc6htkn4/4/
<body>
<p id="one">One</p>
<p id="two">Two</p>
<p id="three">Three</p>
<p id="four">Four</p>
<p>
<button onclick="changeId()">Try it</button>
</p>
</body>
#one {
color: red;
}
#two {
color: blue;
}
function changeId() {
var el = document.getElementById('one');
el.id = 'two';
}
What is wrong with the code? It appears to be correct. I am simply trying to change the id on a click event.
Thanks!
Edit: My settings were not appropriately set in jsfiddle
You code is fine, you just need to change the way jsfiddle loads the js code.
Click on "javascript" button and select "Load Type" to be "No wrap - in <body>"
Working example: https://jsfiddle.net/xc6htkn4/5/

Copying stored text in a table and then display it back into a textarea

I need your help,
How can I go about copying text (with the line breaks included) from my table and put it back into the textarea “newtext”
My existing coding doesn't seem to be working.
<html>
<head>
<style type="text/css">
.box { width: 400px; height: 50px; }
</style>
<script type="text/javascript">
function ta() {
taValue = document.getElementById("ta").value
taValue = taValue.replace(/\n/g, '<br/>')
document.getElementById("tatext").innerHTML = taValue
}
function text2area() {
document.getElementById("newtext").innerHTML = document.getElementById("tatext").innerHTML
}
</script>
</head>
<textarea class="box" id="ta" onkeyup="ta()"></textarea>
<table id="tatable"><tr><td><div id="tatext"></div></td></tr></table>
<br>
<input type="button" onclick="text2area()" value="move text">
<br><br>
<textarea class="box" id="newtext"></textarea>
</html>
Instead of using the function innerHTML, grab the value of the text area you want to capture, and set the value of the new text area to this. You are already using value for the variable taValue. Also, it's better practice to use addEventListener for your clicks and keyups.
function ta() {
taValue = document.getElementById("ta").value
taValue = taValue.replace(/\n/g, '<br/>')
document.getElementById("tatext").value = taValue;
}
function text2area() {
taValue = document.getElementById("ta").value;
document.getElementById("newtext").value = taValue;
}
document.getElementById("ta").addEventListener ("onkeyup", ta, false);
document.getElementById("move-text").addEventListener ("click", text2area, false);
JSFiddle: http://jsfiddle.net/tMJ84/1/
textarea does not have an innerHTML. Notice how you grabbed the value? Set it the same way! It is like this because it is a form element.
document.getElementById("tatext").value = taValue; //semi-colons are just good practice
and here:
document.getElementById("newtext").value = document.getElementById("tatext").value;

Creating a div element inside a div element in javascript

I'm trying a very basic example of creating a div inside an already existing div.
It doesn't seem to be working when I use:
document.getElementbyId('lc').appendChild(element)
but works fine when I do this:
document.body.appendChild(element)
Do I need to add windows.onload function? Though it doesn't work even then!
HTML code:
<body>
<input id="filter" type="text" placeholder="Enter your filter text here.." onkeyup = "test()" />
<div id="lc">
</div>
</body>
JS code:
function test()
{
var element = document.createElement("div");
element.appendChild(document.createTextNode('The man who mistook his wife for a hat'));
document.getElementbyId('lc').appendChild(element);
//document.body.appendChild(element);
}
Your code works well you just mistyped this line of code:
document.getElementbyId('lc').appendChild(element);
change it with this: (The "B" should be capitalized.)
document.getElementById('lc').appendChild(element);
HERE IS MY EXAMPLE:
<html>
<head>
<script>
function test() {
var element = document.createElement("div");
element.appendChild(document.createTextNode('The man who mistook his wife for a hat'));
document.getElementById('lc').appendChild(element);
}
</script>
</head>
<body>
<input id="filter" type="text" placeholder="Enter your filter text here.." onkeyup = "test()" />
<div id="lc" style="background: blue; height: 150px; width: 150px;
}" onclick="test();">
</div>
</body>
</html>
'b' should be in capital letter in document.getElementById modified code jsfiddle
function test()
{
var element = document.createElement("div");
element.appendChild(document.createTextNode('The man who mistook his wife for a hat'));
document.getElementById('lc').appendChild(element);
//document.body.appendChild(element);
}
Yes, you either need to do this onload or in a <script> tag after the closing </body> tag, when the lc element is already found in the document's DOM tree.

Categories