Manipulating DOM in Javascript not working out [duplicate] - javascript

This question already has answers here:
Which characters are valid in CSS class names/selectors?
(11 answers)
Closed 4 years ago.
Hi I'm trying to create a simple calculator website, and I'm trying to manipulate the DOM to display an updating equation, but it won't add the child to the display container.
HTML:
<body>
<div class="body">
<div id="display"></div>
In the Javascript, I have the following code to add an element to the "display" div:
JAVASCRIPT:
const display = document.querySelector("#display");
var eqnDisp = document.createElement("p");
eqnDisp.classList.add("eqnDisp");
eqnDisp.textContent = "DISPLAY SOMETHING";
display.appendChild(eqnDisp);
Am I missing a line? I have the exact code for another page and it works but not here.

The example you provided is finely working:
const display = document.querySelector("#display");
var eqnDisp = document.createElement("p");
eqnDisp.classList.add("eqnDisp");
eqnDisp.textContent = "DISPLAY SOMETHING";
display.appendChild(eqnDisp);
<div class="body">
<div id="display"></div>
</div>
Your <script> tag needs to be placed after the body content, not in the <head> section. This is because you must wait for the DOM to get loaded before you can use DOM methods such as document.querySelector() (i.e. at the point where your script is executing, document is undefined). If you still want your script file in the <head> section, modify it this way:
window.onload = function() {
const display = document.querySelector("#display");
var eqnDisp = document.createElement("p");
eqnDisp.classList.add("eqnDisp");
eqnDisp.textContent = "DISPLAY SOMETHING";
display.appendChild(eqnDisp);
}
However, the code you posted here is not causing the problem. There are many other errors in the JSFiddle you provided. Here are the errors:
let btn1 = document.querySelector("#1");
As stated earlier, this won't work with IDs starting with a number. Correct is using document.getElementById()
btn1.addEventListener("click", include("1"));
This is another mistake. The above line will only call include("1") once, and not on every click. This is not how you pass a parameter to a function inside an event listener. Correct is using
btn1.addEventListener("click", function() {
include("1");
});
...which will call include("1") whenever btn1 is clicked.
btnCLR.addEventListener("click", clearDisp());
If you want to call a function without parameters, remove the brackets. Only call clearDisp, not clearDisp().
equation.concat(value);
equation is a string, not an array. Use the normal addition (concatentation) operator:
equation += value;
Then, you have many functions inside event listeners which you didn't define. Either define these functions, or comment out the whole event listener. You will end up with a working calculator.

Related

How to get text/val from a list of things using Jquery

I have customized the wp_get_archive added a class="tlyear" to its tag.
and using jquery to get each of the years
var y = jQuery('.tlyear');
var m = jQuery('.tlyear').text();
jQuery('.tlyear').click(function() {
alert(m);
});
when I click on one of the it supposes to return the alert text as 1955 but instead, it returns me a whole string of years as "19481955". How do I get the years only from the I click on? since all the has the same class.
You want to get the text of the just the clicked item, so make use of this, which refers to that item:
jQuery('.tlyear').click(function() {
alert(jQuery(this).text());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="tlyear">1948</div>
<div class="tlyear">1955</div>
<div class="tlyear">1963</div>
(Or it may make sense to use jQuery(this).find('a').text(), because you're binding the click handlers to the containing divs, not to the anchor elements that have the text you want, though it doesn't really matter if there are no other elements within those divs.)
In your code, this line:
var m = jQuery('.tlyear').text();
...gets the text of all of the matching elements with no relation to which one(s) might later be clicked on.

Understanding "order matters" on external .js files in html

EDIT:
Okay, gonna try to use as little code as possible to explain my problem.
I have a select dropdown menu that has a function changetext() tied to it. Whenever a value is selected in the dropdown menu, text inside a tag is changed.
The script to the function is stored in an external js file and is placed at the bottom of my html file.
Inside the js file is something like this.
var selectormenu = document.getElementById("selector");
var spanTag = document.getElementById("texthere");
function changetext(){
if(selectormenu.value == "one"){
spanTag.innerHTML = "one";
}
}
By using this js file, I get a TypeError in my browser console. However, if I place var selectormenu and spanTag inside the function, the script works.
EDIT: Since the question case sensitivity was fixed, I am adjusting my answer. You need the DOM element to already be created, because document.getElementById needs to have something to select. Then, your function needs to be named before the parentheses. Finally, you need to call the function, because it won't run unless it's called.
<div id="divid>Hello World!</div>
<script>
var soandso = document.getElementById("divid");
function statsChange() {
soandso.innerHTML = "123";
}
statsChange();
</script>

Creating a div within an existing div in javascript issues

I have a problem, I wanted to create a div in html as a container and in javascript create new divs within the container based on a number input from a user prompt.
My html and javascript look like this.
HTML:
<!doctype html>
<html>
<head>
<link rel="stylesheet" href="stylesheet.css">
<title>Sketchpad</title>
</head>
<body>
<button type="button">Reset</button>
<div class= "container">
</div>
<script src="javascript.js"></script>
<script src="jQuery.js"></script>
</body>
JS
var row = prompt("Enter number of rows:");
var column = prompt("Enter number of columns:");
function createGrid(){
var cont = document.getElementsByClassName('container');
for(i=1; i<column; i++){
var sketchSquare = document.createElement('div');
cont.appendChild(sketchSquare);
}
}
createGrid(column);
I end up with this error: Uncaught TypeError: cont.appendChild is not a function.
I imagine this is something to do with the getElementsByClassName?
I do have a solution which involves creating the container div in javascript and appending the smaller squares inside the container div. I was just curious as to why my first soltuion didn't work?
cont[0].appendChild(myDiv) is a function.
When you document.getElements By Class Name as the name implies you are getting many elements (an array of sorts) of elements and this array don't have the same functions as each of its elements.
Like this:
var thinkers = [
{think: function(){console.log('thinking');}
];
thinkers don't have the method .think
but thinkers[0].think() will work.
try this: open your javascript console by right clicking and doing inspect element:
then type:
var blah = document.getElementsByClassName('show-votes');
blah[0].appendChild(document.createElement('div'));
It works!
also if you want to use jQuery which I do see you added...
you can do:
var cont = $('container');
cont.append('<div class="sketchSquare"></div>');
Try that out by doing this:
First get an environment that has jQuery.
Hmm maybe the jQuery docs have jQuery loaded!
They do: http://api.jquery.com/append/.
Open the console there and at the bottom where the console cursor is type:
$('.signature').append('<div style="background: pink; width: 300px; height: 300px"></div>');
You'll notice that you add pink boxes of about 300px^2 to 2 boxes each of which have the "signature" class.
By the way, prompt gives you a string so you'll have to do row = Number(row); or row = parseInt(row, 10); and another thing don't use that global i do for(var i = 0; ...
var cont = document.getElementsByClassName('container');
Because that^ doesn't return a node, it'll return an HTMLCollection.
https://www.w3.org/TR/2011/WD-html5-author-20110705/common-dom-interfaces.html#htmlcollection-0
You need to pick an individual node from that collection before appending.
There could be a couple of issues that could cause this. Without fully giving the answer here's what it could be at a high level.
Your script is ran before the DOM is fully loaded. Make sure that your script is ran after the DOM is present in the page. This can be accomplished using either the DOMReady event ($(document).ready equivalent without jQuery) or simply making sure your script tag is the last element before the closing body tag. (I usually prefer the former)
When you utilize document.getElementsByClassName('container') (https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName) this method returns an array therefore you would either need to apply the operation to all elements of the result or just select the zero-th as document.getElementsByClassName('container')[0]. As an alternative, if you would like to be more explicit you could also place an id on the container element instead to more explicitly state which element you would like to retrieve. Then, you would simply use document.getElementById([id]) (https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById) and this would get back a single element not a collection.
The result of prompt is a string. Therefore you would have to first parse it as an integer with parseInt(result, 10) where 10 is simply the radix or more simply you want a number that is from 0-10.
You should include jquery library before your script, it`s important
<script src="jQuery.js"></script>
<script src="javascript.js"></script>

How to apply a click function, that changes the clicked div, to new div elements that are created

At the moment I am using the following code which on the click of an HTML div element, changes the inner text to "Hello World":
<div id = "one" onclick = "click('one')" >text</div>
<script>
function click(id){
document.getElementById(id).innerHTML = "Hello World";
}
</script>
This works as expected and changes the content of the div to "Hello World".
The problem I am facing is at the moment I am using the id as a parameter input for the function and so that also means that for each div element that I create I would have to manually write its id within the onclick function.
I am able to create div elements using the following script which takes a value from an HTML input box, turns into a number then uses that number in a for loop to create as many div elements as specified:
<script>
function numberOfDivs(){
var divValue = parseInt(document.getElementById("inputbox").value, 10);
for(var i = 1; i < divValue + 1; i++){
var newDiv = document.createElement("div");
var divText = document.createTextNode("text")
//newDiv.setAttribute("onclick", "click()");
newDiv.appendChild(divText);
var whatIAmAppendingTo = document.getElementById("one");
whatIAmAppendingTo.appendChild(newDiv);
}
</script>
Now the problem that I having is applying that click() function to any of the new div elements that have just been created so that the click() function only affects the div that I have clicked on. I have included the setAttribute line when I create the new div elements so there is no problem linking it to the click() function.
I believe that there are two options:
-Either create new code within the numberOfDivs() function and use the var i to create an id that would be different for each new div element that I create, since var i increases to a different value each time the for loop repeats.
or
-Rewrite the click() function so that instead of having to use an id paramater I can instead make the function applicable to all div's. I was roughly thinking along the lines of using the 'this' keyword within that code, or anything along those lines so that it applies to only the div element that I click on.
With both of these possible solutions I'm not quite sure how to execute them so it would be great help if someone would be able to give me an example how it works.
Any questions or clarifications feel free to ask.
The problem I am facing is at the moment I am having to use the id as a parameter input for the function ...
No, you don't; you can pass this into your function, which is a reference to the div the click occurred on:
<div id = "one" onclick = click(this) >text</div>
Then in your function, use that argument rather than document.getElementById(id):
function click(div){
div.innerHTML = "Hello World";
}
Now you can use the same function for multiple divs.
Note, though, that if you're creating the divs programmatically, there's a better answer than setting the onclick attribute: addEventListener (attachEvent on older versions of IE). In your function creating divs:
var newDiv = document.createElement("div");
var divText = document.createTextNode("text")
if (newDiv.addEventListener) {
newDiv.addEventListener("click", click, false);
}
else {
newDiv.attachEvent("onclick", click);
}
Within click, use this:
function click(){
this.innerHTML = "Hello World";
}
typo in innerHTML and onClick
text
<script>
function click(id){
document.getElementById(id).innerHTML = "Hello World";
}
</script>
and
<div id = "one" onClick ="click('one')" >text</div>
Could this idea be helpful? Create your divs as (example for id='one'):
<div class='mydivs' id='one' ></div>
And then, detect the click on the div using a class and one event handler using JQuery:
$(".mydivs").click( function() {
id = $(this).attr('id');
click(id);
});
<div id="one">
<!-- dynamically added child nodes -->
</div>
<script>
$.ready(function(){
$('#one').children().livequery('click', function(event){
this.innerHTML = "Hello world";
});
});
<script>
Here we can use livequery to add click handlers to child elements that will be added dynamically.
if you provide your newly created divs with a common class e.g. clickable you could do this
$function(){
//Any click event of the body element that originates from a ".clickable"
//will be handled by the provided handler
$("body").on("click",".clickable",function(){
$(this).html("Hello world");
});
//... anything else that has to happen on document ready
});

Searching jQuery variable full of html [duplicate]

This question already has answers here:
parse html string with jquery
(4 answers)
Closed 8 years ago.
This may be a strange question -- Right now I have a variable that is full of HTML, and I want to use jQuery (or JS) to search that varaible for inputs with checkboxes, and return the information.
So:
alert($(this).parent().parent().html())
var thisIsThat = $(this).parent().parent().html();
alert(thisIsThat)
var Awesome = $(thisIsThat).find('input:checked');
And then after I get that variable, after a successful ajax call, I want to change a specific attribute inside of it, like so:
$(Awesome).attr('value', 'false');
Right now, "Awesome" is returning nothing, which then doesn't allow me to change the attribute like I want to. I may be on the wrong direction as well -- any advice appreciated!
Use this
var thisIsThat = $(this).parent().parent();
alert(thisIsThat)
var Awesome = $(thisIsThat).find('input:checked');
In this case thisIsThat is a object and you can find anything using that object
This is an example showing the same basic idea running off of a string which finds the checkbox fine and unchecks it.
<div id="out"></div>​
<script>
var htmlStr = '<div><input type="checkbox" checked="checked"/></div>';
var temp = $(htmlStr);
var cb = temp.find("input:checked");
cb.attr("checked",false);
jQuery("#out").append(cb);
</script>
jsfiddle
The problem I am betting is that you are checking the checkbox manually. It will not update the DOM attribute when you do that.
Here is a basic example to show you the problem.
<div id="one">
<input type="checkbox" />
</div>
<button>Tell</button>​
<script>
function tellMe(){
var myDiv = jQuery("#one");
var html1 = myDiv.html();
console.log(html1);
}
jQuery("button").click(tellMe);
</script>
Take a look this fiddle of the code above.
Open up the console, and click on the button. You will see it unchecked. Check the checbox and click the button again, same html is outputted even though the checkbox is checked.
change
var Awesome = $(thisIsThat).find('input:checked');
to
var Awesome = $(thisIsThat).find('input[type=checked]');
now loop over it
Awesome.each(function(){
if($(this).is(':checked'))
{
$(this).attr('checked',false);
}
});

Categories