HTML element not detected in external .js file [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 4 years ago.
My HTML code:
<div class="container">
<div class="question-card">
<h1 id="question1">This is the question</h1>
</div>
<div class="answer-choices">
<div class="row1">
<span class="choice1" id="one" onclick="choice1()">One</span>
<span class="choice2" onclick="choice2()">Two</span>
</div>
<div class="row2">
<span class="choice3" onclick="choice3()">Three</span>
<span class="choice4" onclick="choice4()">Four</span>
</div>
</div>
<button id="btn" onclick="next()">Next</button>
My js code:
function clickNextText(){
document.getElementById("question1").innerHTML="Answer recorded, Click next to proceed"
} //This is working fine
var str
element = document.getElementById('btn');
if (element != null) {
str = element.value;
}
else {
str = null;
}
console.log(str) //This is however returning null.
I don't understand what is wrong here. Moreover every element with an id after the div with class answer-choices isn't detected. While the script code when placed in .html itself works fine.

Likely your javascript is running before the page has loaded. Try wrapping your whole javascript logic in a function and running it on window.load.
i.e.
window.load = function () {
// your code here
}

first change your function name on click from next() to clickNextText()
<button id="btn" onclick="clickNextText();">Next</button>
then use this code in javascript instead of :
function clickNextText(){
document.getElementById("question1").innerHTML="Answer recorded, Click next to proceed"
}
document.onload = function(){
var str
element = document.getElementById('btn');
if (element != null) {
str = element.value;
}
else {
str = null;
}
console.log(str);
};

Related

How to swap contents of header tag - HTML/Javascript

I have the following:
function changeFirst() {
let p = document.getElementById("firstElement")[0].innerhtml;
alert(p);
if (p = "<h1>This is the 1st element</h1>") {
document.getElementById("firstElement").innerHTML = "<h1>Changed first</h1>"
} else {
document.getElementById("firstElement").innerHTML = "<h1>Switched back first</h1>"
}
}
<div id="firstElement">
<h1>This is the 1st element</h1>
</div>
<button onclick="changeFirst()">Change first element</button>
I basically want the button to alternate the contents of the firstElement div. Why doesn't this work?
Thank you
document.getElementById returns ONE element
Also = is assignment, you want == or === for comparison
Could you possibly mean this:
function changeFirst() {
let h = document.querySelector("#firstElement h1");
h.textContent = h.textContent==="This is the 1st element" ? "Changed first" : "This is the 1st element"
}
<div id="firstElement">
<h1>This is the 1st element</h1>
</div>
<button type="button" onclick="changeFirst()">Change first element</button>
Here is exactly what you asked for. You were close.
1) when including javascript, you can just use script tags and it will work fine, when you use JSON or JQuery, that's when you have to use an include tag of a .js file. javascript code can be notated with script type = text/javascript.
2) when making a comparison in javascript: use three equal signs (===)
when making a non variable type-sensitive comparison: use two equal signs (==)
when setting a variable: use one equal sign (=)
https://www.geeksforgeeks.org/difference-between-and-operator-in-javascript/
3) When calling dynamic header, it is not an array, so you don't need [0], you are just comparing the innerhtml of the dynamic header div and it is only one header, arrays are for multiple things. Keep working on code, as you seem to have a good start, and made some minor syntax errors.
<!DOCTYPE html>
<html>
<body>
<button onclick="changeHeader()">Click me</button>
<div id="dynamicHeader"><h1>Hello World</h1></div>
<p>Clicking the button changes the header.</p>
<script>
function changeHeader() {
if (document.getElementById("dynamicHeader").innerHTML === "<h1>Hello World</h1>") {
document.getElementById("dynamicHeader").innerHTML = "<h1>Goodbye World</h1>";
} else {
document.getElementById("dynamicHeader").innerHTML = "<h1>Hello World</h1>"
}
}
</script>
</body>
</html>
Try like this. Here I introduced a flag and switched it to check content.
var changed = false;
function changeFirst() {
if (!changed) {
changed = true;
document.getElementById("firstElement").innerHTML = "<h1>Changed first</h1>";
} else {
changed = false;
document.getElementById("firstElement").innerHTML = "<h1>Switched back first</h1>";
}
}
<div id="firstElement">
<h1>This is the 1st element</h1>
</div>
<button onclick="changeFirst()">Change first element</button>

Assign variable to an attribute in div tag

I have the following code.
My requirement is to fetch the path that is stored in the myValue variable and assign it to the w3-include-html attribute in div tag.
However, I am not able to assign the path presented in myValue to the w3-include-html attribute in the div tag.
I tried the solutions presented in Javascript variables in HTML attributes. This link discusses about img tag. I tried the same solutions for div tag but unable to solve my problem.
Any suggestions would be appreciated.
<script>
var myValue = "Tables/"+"FileName"+".html";
</script>
<div id="openModal" class="modalDialog">
<div>
X
<div w3-include-html=myValue></div>
</div>
</div>
You could create a function that assigns the value (via setAttribute) to the div any time the function is fired:
var myValue = 'Tables/' + 'FileName' + '.html';
var div = document.querySelector('div[w3-include-html]');
console.log('Value before function call: ' + div.getAttribute('w3-include-html'));
insertMyValue();
console.log('Value after function call: ' + div.getAttribute('w3-include-html'));
function insertMyValue() {
div.setAttribute('w3-include-html', myValue);
}
<div id="openModal" class="modalDialog">
<div>
X
<div w3-include-html="myValue"></div>
</div>
</div>
I solved this problem by adding the id as shown below:
<div id="openModal" class="modalDialog">
<div>
X
<div id="schema"></div>
</div>
</div>
<script>
var myValue = "Tables/"+"Thing"+".html";
document.getElementById("schema").setAttribute('w3-include-html',myValue);
</script>
I think you can add an interval and check value and it will check updates automatically.
Some code example:
var myValue = "Tables/"+"FileName"+".html", element = document.querySelector('div[w3-include-html]');
function checkUpdate () {
if (myValue !== element.getAttribute('w3-include-html')) {
element.setAttribute('w3-include-html', myValue)
console.log('updated to %s', myValue);
}
};
setInterval(checkUpdate, 100);
setTimeout(() => myValue = "Test", 200); // only for example of update.
<div id="openModal" class="modalDialog">
<div>
X
<div w3-include-html=myValue></div>
</div>
</div>

Deleting the last Element in a Div [JavaScript]

I'm having a strange problem. I'm trying to make a program that will add and delete div's inside another div called "body". To add divs, I use document.getElementById("body").innerHTML. Adding works fine. However, in the deleting function, I replace the "body" id with a variable with the id of the div that will be deleted. But when I run the code, I get the error "cannot set innerHTML of null". I tried to replace the id variable with a fixed local variable, and it worked fine. I also tried to add quotes to the variable but that didn't work either. Is there any reason why I can't set the id to a changing variable? Thanks.
Here is my code:
var i = 1;
function myFunction() {
var addDiv = document.getElementById("body2");
addDiv.innerHTML += "<div id = '" + i + "'><br><textarea id = '1' > foo < /textarea></div > ";
i++;
}
function myFunction2() {
var deleteDiv = document.getElementById(i);
deleteDiv.innerHTML = "";
i--;
}
<div id="body2">
<div id="0">
<textarea id="text">lol</textarea><button onclick="myFunction()">Add</button>
<button onclick="myFunction2()">Delete</button>
</div>
</div>
you are incrementing i after adding a div so you must use i-1 while deleting to get correct id.
var i = 1;
function myFunction() {
var addDiv = document.getElementById("body2");
addDiv.innerHTML += "<div id = '"+i+"'><br><textarea id = '1'>foo</textarea></div>";
i++;
}
function myFunction2() {
var deleteDiv = document.getElementById(i-1);
deleteDiv.remove();
i--;
}
<div id = "body2">
<div id = "0">
<textarea id = "text">lol</textarea><button onclick =
"myFunction()">Add</button>
<button onclick = "myFunction2()">Delete</button>
</div>
</div>
To remove last child, you can even use CSS selector last-child. You should also add specific class to newly added divs as you would want to remove only newly added divs.
This will also remove dependency of i.
As an addon, you can also use document.createElement + Node.appendChild instead of setting innerHTML. .innerHTMl will be expensive for highly nested structure.
function myFunction() {
document.getElementById("body2").appendChild(getDiv());
}
function getDiv(i){
var div = document.createElement('div');
div.classList.add('inner')
var ta = document.createElement('textarea');
ta.textContent = 'foo';
div.appendChild(ta);
return div;
}
function myFunction2() {
var div = document.querySelector('#body2 div.inner:last-child')
div && div.remove()
}
<div id="body2">
<div id="0">
<textarea id="text">lol</textarea><button onclick="myFunction()">Add</button>
<button onclick="myFunction2()">Delete</button>
</div>
</div>
You can refer "innerHTML += ..." vs "appendChild(txtNode)" for more information.

Hide/show images button JS

I have a webpage where i have 3 images and I have a button to hide those images all at once on click, and then show them(this part is not implemented yet). I have a JS function for hiding them but it is not working and I have no idea why. So this is part of my code:
<div id="left"><img id="leftimage" name="leftimage" src="pic1url.jpg" style=
"visibility:visible"></div>
<div id="centerright">
<div id="center"><img id="centerimage" name="centerimage" src="pic2url.jpg"
style="visibility:visible"></div>
<div id="right"><img id="rightimage" name="rightimage" src="pic2url.jpg"
style="visibility:visible"></div>
</div><script type="text/javascript">
var hideShowButton = document.getELementById("hideShowButton");
hideShowButton.onclick = function()
{
var allImages = { left:"leftimage"; center:"centerimage"; right:"rightimage"};
if(document.getElementById("leftimage").style.visibility == 'visible')
{
for ( var image in allImages)
{ document.getElementById(allImages[image]).style.visibility = 'hidden';
document.getElementById(allImages[image+"1"]).style.visibility = 'hidden';
document.getElementById(allImages[image+"2"]).style.visibility = 'hidden';
}
document.getElementById("hideShowButton").innerHTML = "Mostrar imagens";
}
}
</script>
<div id="buttons">
<input id="hideShowButton" type="button" value="Hide Pics">
</div>
Before reading the answer, I highly suggest you learn how to use the browser's console. It will print all the errors that make your JavaScript code to crash. I also suggest you take some time to read JavaScript tutorials :)
There are many things wrong with your code. First, there is a typo "getELementById" (L is uppercase instead of lowercase). Second, you need to place the script tags bellow your button. Third, when creating an object, you should separate it's properties using commas (,) not semicolons (;) . Finally, you made a false use of the for loop. Just to help you out, here is the corrected code but don't expect people to do that for you every time. You need to find mistakes like these on your own in the future :)
<div id="left">
<img src="pic1url.jpg" id="leftimage" style="visibility:visible" />
</div>
<div id="centerright">
<div id="center">
<img src="pic2url.jpg" id="centerimage" style="visibility:visible"/>
</div>
<div id="right">
<img src="pic2url.jpg" id="rightimage" style="visibility:visible"/>
</div>
</div>
<div id="buttons">
<input type="button" value="Hide Pics" id="hideShowButton" />
</div>
<script type="text/javascript">
var hideShowButton = document.getElementById("hideShowButton");
hideShowButton.onclick = function()
{
var allImages = { left:"leftimage", center:"centerimage", right:"rightimage"};
if(document.getElementById("leftimage").style.visibility == 'visible')
{
for ( var image in allImages)
{
document.getElementById(allImages[image]).style.visibility = 'hidden';
}
document.getElementById("hideShowButton").innerHTML = "Mostrar imagens";
}
}
</script>
Use can use diplay none or block property of css to hide and show any view respectively
<img id="one" src="pic1url.jpg" style="display:none;" />
Through javascript you can use this
document.getElementById(one).style.display = 'none';
Sorry, but your code is a bit messy. Why are you using a for statement if then you try to hide every image every time?
By the way, you're misusing the for...in statement. AllImages is a asociative array with no numeric indexes. for (var image in AllImages), image will be 'left', then 'center', then 'right' (the names of the properties of the object you're using). So a statement like
AllImages[image+1]
will return 'undefined' and your code will throw an error. Your code should look like this:
hideShowButton.onclick = function()
{
var allImages = { left:"leftimage"; center:"centerimage"; right:"rightimage"};
if(document.getElementById("leftimage").style.visibility == 'visible')
{
for ( var image in allImages)
{
document.getElementById(allImages[image]).style.visibility = 'hidden';
}
document.getElementById("hideShowButton").innerHTML = "Mostrar imagens";
}
}
By the way, I suggest you to read some documentation about loops in javascript, like MDN

Can't insert a div into another internal div

I need your help to solve a problem I have.
I have this code:
<div id="div1" >
<div id="edit1">
hello
<input type="button" id="b1" onclick="aaa()"/>
</div>
</div>
I want to use insert into the internal div (id=edit1) another new div I generated.
I tried alike code but it's not running:
js:
function aaa()
{
var elem = createDivLine();
var el1 = document.getElementById("div1");
var el2 = el1.getElementById("edit1");
el2.appendChild(elem);
}
function createDivLine()
{
var tempDiv1 = document.createElement("div");
tempDiv1.innerHTML = "Sam";
return tempDiv1;
}
The result should looks like this:
<div id="div1" >
<div id="edit1">
hello
<input type="button" id="b1" onclick="createDivTable()"/>
<div>"Sam"</div>
</div>
</div>
JSFiddle: http://jsfiddle.net/KknXF/
Since IDs are unique, it is not valid to attempt to get an element's children by ID.
Remove this line:
var el1 = document.getElementById('div1');
And change the following line to:
var el2 = document.getElementById('edit1');
In the event that you have some irrepairably (I can never spell that word...) broken HTML that you can't possibly change, try this:
var el2 = document.querySelector("#div1 #edit1");
It should be
function aaa() {
var elem = createDivLine();
var el2 = document.getElementById("edit1");
el2.appendChild(elem);
}
Demo: Fiddle

Categories