Access Value of HTML Element Created in Javascript - javascript

EDIT: This question is not a duplicate, I am aware that at this point foo has not been inserted into the DOM. My question is whether or not is is possible to access the elements declared in the string assigned to foo without inserting it into the document object.
In the following code, we declare an HTML element as a JavaScript variable.
<script>
var foo = "<td id = 'bar'>";
</script>
Now, after the <script> tag but before the </script> tag, how do I access the value of id in the table cell?
Eg. calling console.log(foo.id) obviously prints undefined.
how could I call the console.log() function (or any other function to access the value of id) to give us the correct value, "bar"?
Im using <td> as an example but I assume this applies to any html tag declared with JS.

In your case you'd get what's between the first and second ', which coincidentally happens to be the id by doing:
foo.split("'")[1] // -> bar
However that is not too useful or reusable. You could push an element to memory and set the innerHTML of that node to your string, however the string in your example is not valid HTML, so it would not work.
var temp = document.createElement('html')
temp.innerHTML = str
temp.getElementsByTagName('td')[0].id // -> bar
Can't imagine your use case though, so maybe none are perfect.

Related

The reasoning behind direct link between DOM Element and the variable it is assigned?

I am kinda newbie and I really want to understand why the variables we create don't just get the values inside the DOM element, but becomes the DOM element?
Here is some basic code;
var elementValues = document.getElementById("p1");
elementValues.style.color = "red";
// I don't understand why we don't need this step in order to manipulate the DOM.
// document.getElementById.getElementById("p1") = elementValues;
Aren't we basically saying to copy the values from DOM element with an id of p1 and paste them into elementValues?
But why the color of DOM element changes when I change the color of elementValues? From what I understand it acts like a pointer.
In Javascript, Object variables store a reference to the objects. Hence, document.getElementById returns a reference. So when you modify the values of elementsValues, your are editing the referenced object.
Have a look on Working with Objects - Comparing Object. You could read the whole page also to have an overview.
Yes, it is like a pointer.
By using var elementValues = document.getElementById("p1"); you are assigning a reference to the DOM element to the variable. Nothing about the element gets saved to the variable, but "where to find it".

javascript - Global variable not working

I have a variable that I want saved so that multiple functions can use it. I followed w3schools's directions but it doesn't work. Am I forgetting something? Thank you in advance.
var name = document.getElementById('name').value;
function complete() {
document.getElementById('demo').innerHTML = name;
}
There are a few things to consider:
If you have code that attempts to find an element, but that element hasn't even been read by the browser yet, the browser won't be able to find it. So, make sure that your code only runs AFTER the full DOM has been loaded
by placing the script just before the closing body tag.
Don't attempt to get the value of a form field as soon as the page
loads because the user hasn't typed anything into it yet, so the
value will be nothing. You need to set up your code so that your function gets called at the right time (after the user has had a chance to type in the form field) so only get the value when that moment has come.
Don't give any element the name name because the Global window
object has a property called name that defaults to an empty string
and when you attempt to access name, it could incorrectly attempt
to get the window.name instead of your element called name.
Only form fields have a value property. All other elements have
.textContent (used when the string does not contain any HTML or you
want the actual HTML code displayed, rather than parsed) and
.innerHTML (used when the string does contain HTML and you want
that code parsed).
Lastly, do yourself a favor and don't use W3Schools. It is well known to have outdated or flat out wrong information on it. Instead use the Mozilla Developer's Network, which is recognized as one of the best resources for client-side web development documentation.
<input type="text" id="userName">
<input type="button" value="Click Me!" id="btn">
<div id="demo"></div>
<script>
// Set up the button's click event handling function
document.getElementById("btn").addEventListener("click", complete);
// Only get a reference to the element, not its value because, at this point,
// the user hasn't had a chance to type anything into it.
// Also, getting a reference to the element is the best approach because, if
// you decide you want some other property of the same element later, you'd have
// to scan the document for the same element again.
var theName = document.getElementById('userName');
function complete() {
// Now, just get the current value of the textbox at this moment in time
document.getElementById('demo').textContent = theName.value;
}
</script>

Why am I getting "TypeError: Cannot read property 'value' of null" when using getElementById?

In the following code:
function Transact() {
if(document.getElementById('itctobuy').value!='') {
itctobuy = parseInt(document.getElementById('itctobuy').value);
}
if(document.getElementById('steamtobuy').value!='') {
steamtobuy = parseInt(document.getElementById('steamtobuy').value);
}
if(document.getElementById('reltobuy').value!='') {
reltobuy = parseInt(document.getElementById('reltobuy').value);
}
if(document.getElementById('airtobuy').value!='') {
airtobuy = parseInt(document.getElementById('airtobuy').value);
}
if(document.getElementById('bsnltobuy').value!='') {
bsnltobuy = parseInt(document.getElementById('bsnltobuy').value);
}
updateValues();
}
The function's executed by a simple onclick of a button. There are 5 textarea elements and the user may input a number in any, and upon clicking the button the value should be stored in these vars if the textarea value isn't empty (Although it doesn't work even if the empty condition is not present).
If I remove the entire block, updateValues() executes fine, whereas putting it back causes it not be executed, so the problem's with it. What's the reason for this and how do I fix this?
Edit: The console says the following:
Uncaught TypeError: Cannot read property 'value' of null at TRANSACT at HTMLButtonElement.onclick
So what's the cause of this error? It doesn't work when I input all text fields and their values are not null.
Uncaught TypeError: Cannot read property 'value' of null
That tells you that at least one of those elements doesn't exist as of when that code runs, so getElementById returns null, which you're trying to read the value property from.
getElementById will only return null if no element with the given ID exists in the document as of when you call it. In general, the reasons for the element not existing fall into these categories:
Calling getElementById too early
Misspelling the id (e.g., a typo)
Using a name instead of an id
The element exists, but isn't in the document (rare)
In your case, since this is on button click, it's probably #2 or #3. You can see which ID it's unhappy about by looking at the line the error identifies, or using your browser's debugger to step through the code statement-by-statement.
Let's look at each category:
1. Calling getElementById too early
One common error is to have code calling getElementById in a script block that's before the element in the HTML, like this:
<script>
document.getElementById("foo").innerHTML = "bar";
</script>
<!-- ...and later... -->
<div id="foo"></div>
The element doesn't exist as of when that code runs.
Solutions:
Move the script to the end of the HTML, just before the closing </body. tag
Put your call to getElementById in a callback, such as on the DOMContentLoaded event, or a button click , etc.
Don't use window.onload or <body onload="..."> unless you really want to wait to run the code until all external resources (including all images) have been loaded.
2. Misspelling the id
This is really common, using getElementById("ofo") when the element is defined with id="foo".
Example:
<div id="foo"></div>
<script>
document.getElementById("ofo").innerHTML = "I'm foo"; // Error
</script>
Solution: Use the right ID. :-)
3. Using a name instead of an id
getElementById("foo") looks for an element with id="foo", not with name="foo". name != id.
Example:
<input name="foo" type="text">
<script>
document.getElementById("foo").value = "I'm foo"; // Error
</script>
Solution: Use id, not name. :-) (Or look up the element with document.querySelector('[name="foo"]').)
4. The element exists, but isn't in the document
getElementById looks in the document for the element. So if the element has been created, but has not been added to the document anywhere, it won't find it.
Example:
var div = document.createElement("div");
div.id = "foo";
console.log(document.getElementById("foo")); // null
It doesn't look throughout memory, it just looks in the document (and specifically, the document you call it on; different frames have different documents, for instance).
Solution: Make sure the element is in the document; perhaps you forgot to append it after creating it? (But in the example above, you already have a reference to it, so you don't need getElementById at all.)

Undefined Array in JQuery/JavaScript

I'm having some trouble with the following piece of code:
I would like to be able to view the contents of $prisonlist in the console
I would like to be able to view the contents of $prisonlist (or $prisonlist[some value]) in the console, and to display it in the text of the div.
Essentially, whenever I do, it comes up with an error known as "undefined" - although my other functions that work with it seem to work just fine (such as the //
Code:
$counter = 0;
var $prisonlist=[];
$prisonlist[0]=1;
$('#entered').text($prisonlist[0]);
$('#s1').click(function(){
$(this).toggleClass('on off');
$counter = $counter + 1;
$('#clicks').text($counter);
$prisn = Math.ceil(Math.random()*10);
$('#prisoners').text($prisn);
$boo=$prisonlist.indexOf($prisn) //finds in array whether there is any
if ($boo==-1){
$prisonlist.push($prisn); // lists the individual inside
}
});
The declaration var $prisonlist=[];is scoped, therefore unavailable in the console where you can see only global stuff. The solutions are:
Quick yet ugly - declare $prisonlist=[]; (without the var) in the global scope.
My preferred - wherever you want to inspect the variable insert console.log($prisonlist). This will log the current value of the variable to the console.
Use a debugger
From what i can see, you are trying to use an array ($prisonlist) as an argument to the jquery text() function which only takes a string, number, boolean or function (but not an array).
You need to cast the array to a string first using JSON.stringify:
$('#element).text(JSON.stringify($prisonlist));
Ensure that #element isnt an input or textarea element since text() doesn't work on those (use val() instead).

Passing Variables Javascript

I am trying to pass a variable in javascript. I create a link in the following manner and everything seems to be working.
label.innerHTML = ' link';
However when I create the link in the following way where the link would also pass an associated object I get the following error from firebug -> "missing ] after element list"
label.innerHTML = ' link';
Is this an acceptable way to pass an object to a function. The problem is that I am creating this link within a function. The function creates links like this based upon an object that is passed to it. Therefore I cannot have this "object" as a global scope.
You are building the script by mashing together strings, as such you can only work with strings and object will be automatically stringified.
Use DOM instead.
var link = document.createElement('a');
link.href = "#"; // Have a more sensible fall back for status bar readers and middle clickers
link.appendChild(document.createTextNode(' link');
link.addEventListener('click',function () { show_box(this, object); },false);
label.appendChild(link);
… but use a library that abstracts away the non-standard event models that some browsers have.
What you're trying to do is pass the contents of object to output. Since it's an object, the string representation will be something like [object Object]. The output HTML would look like:
link
which is invalid. Don't try to concatenate the object, just pass it along as another argument to the function, like this. Or, better yet, use jQuery:
<!-- somewhere in the head, or at least after the object is defined -->
<script type="text/javascript">
$(function() {
$('#thelink').click(function() { show_box(this, object); });
});
</script>
...
link
If your object is simple variable like numeric or string variable than it will be Ok but if you are passing html object it will not work because it will be something like below.
link

Categories