HTML:
<span class="rbx-text-navbar-right text-header" id="nav-robux-amount">11</span>
CODE:
element = document.getElementById("nav-robux-amount")
if (element){
window.alert(element.value)
}
window.alert shows that the value of element is undefined
The .value property only exists on inputs.
The 'element' isn't a constant variable.
If you want to get the content, you can do the following:
const element = document.getElementById("nav-robux-amount");
if (element) window.alert(element.textContent)
Note: innerHTML is not as good as textContent, as it is vulnerable to attacks.
Related
I am creating an HTML input element in JS, then inserting it into the DOM. However, after it is inserted, the JS element object does not reference the new DOM element.
The element type button element and input type 'submit' work too, but the input element seems to not work with either 'number' or 'text,' which I would be using.
let parent = document.createElement('div');
let child = document.createElement('div');
let childInput = document.createElement('input');
childInput.type = 'text';
childInput.value = 'foobar';
child.append(childInput);
parent.append(child);
document.body.append(parent);
There are no errors, however in chrome dev tools I can see the JS element object is not tied to the DOM object for the input when type is set to text or number. The element IS inserted into the DOM, however it does not reflect the JS object reference, and the value is not inserted into the DOM element, nor would the class, id, etc.
Edit: Also, it does not work when using the appendChild function either.
It sounds like you are trying to change the HTML attributes by setting the JavaScript properties, which doesn't always work. You can use myElement.setAttribute(attributeName, newValue) to change the HTML attributes using JavaScript (and myElement.propertyName = newValue to change the JavaScript properties.)
Note that the initial value of the value attribute is reflected in the defaultValue property. (There are a few other oddball property names like this where reserved words in JS conflict with HTML terms.)
Note also that HTML attributes are case-insensitive, whereas JS properties are case-sensitive -- and kebab-case attributes get mapped to camelCase properties.
Much more info on this can be found here: https://javascript.info/dom-attributes-and-properties
let parent = document.createElement('div');
let child = document.createElement('div');
let childInput = document.createElement('input');
childInput.type = 'text';
childInput.id = 'initialId';
childInput.classList.add('someClass');
childInput.defaultValue = 'initial value';
child.append(childInput);
parent.append(child);
document.body.append(parent);
// Initial attributes
let insertedChild = document.getElementById('initialId');
console.log(insertedChild.outerHTML);
// Modified attributes
insertedChild.setAttribute('id', 'changedId');
console.log("`id` property (reflected from attribute): " + insertedChild.id);
insertedChild.setAttribute('value', 'changedValue');
console.log("`value` property (reflected from attribute): " + insertedChild.value);
console.log(insertedChild.outerHTML);
I have a problem to get DOM element's attributes in JS. Here is code:
return elem.getAttribute(attr) || elem[attr] || "";
elem.getAttribute(attr) is used to get attributes like name or id, elem[attr] is used to get attribute like tagName. It works fine, until style came out.
In my case, I want to have "" when style attribute not set. But with above code, it will try elem[attr] when elem.getAttribute(attr) returns null. So if style is not set, I get all browser supported styles instead of "".
How to deal with this problem? Is there any better way than enum attributes?
Edit:
I want to write a general function to get element's attributes (such as name, style) or properties(such as tagName).
The main difference is elem.getAttribute(attr) try to get an attribute in the tag element, but elem[attr] try to get a property from an object, is important to know that elem inherits all properties from the Element Object, this properties are declared and in some cases defined, one of this properties is style.
In the particular case of the style property, by default this has been defined with an CSSStyleDeclaration, that's the reason you get attributes of style.
If you want only check if the attribute is in the tag, I suggest you only use this code:
return elem.getAttribute(attr) || "";
This is a code I use on my applications, so I'll just copy & paste it:
Object.defineProperty( Element.prototype, "hashAttr", { get: function(){
/* Bekim Bacaj 2008 */
var hash=[], i = 0, x = this.attributes;
while( x[i] ){hash[x[i].name] = x[i++].value};
return hash;
}})
;
which is, to my knowledge, the fastest possible.
This is a sample return from an element that has no inline or JavaScript assigned styles on its tag.:
>> media.hashAttr
{
width : "100%",
height : "100%",
id : "media",
src : "http://*****.***/stream/*****.mp4",
autoplay : "false",
poster : "http://******.***/thumb/*****.jpg",
type : "video/mp4"
}
Notice that, therefore, no offline style-attribute is present in the property list.
I have an answer. It handles tagName specially. It's not great. But it can get the job done.
var value = elem.getAttribute(attr);
if (!value) {
if (attr == "tagName") {
value = elem["tagName"] || "";
} else {
value = "";
}
}
return value;
If I have a text input and have set a default value in the HTML, is there anyway to access the original value after jquery has changed the current value using .val()?
It was my understanding that jQuery should be changing the value property and not the value attribute?
Edit: Note I'm not asking how I could store the default value to retrieve it later (e.g. in data or in a var) I'm interested in why jQuery is modifying the attribute of the input field (and in turn the defaultValue) and not just the property.
For this example:
<input id="me" type="hidden" value="starting value" />
<script>
var $field = $('#me');
console.log($field.val());
console.log($field.prop('defaultValue'));
console.log($field.val('new value'));
console.log($field.val());
console.log($field.prop('defaultValue'));
console.log($field.attr('value'));
console.log($field.prop('value'));
</script>
We see:
starting value
starting value
[input#me, context: document, selector: "#me", jquery: "2.1.0", constructor: function, toArray: function…]
new value
new value
new value
new value
Fiddle:
http://jsfiddle.net/jLsqmxg7/1/
jQuery "val" setter always change both the attribute and the property. They do this to not confuse the developer with a ambiguous behavior. If you really want to change only the property and let the tag attribute with the same value do this:
var $input = $("<input>", {value: 'original'}); // Using the jQuery constructor to create a input :)
$input[0].value = "foo"; // Changing the value property of this HTMLInputElement instance
console.log($input.val()); // foo
console.log($input.prop('value')); // foo
console.log($input.attr('value')); // original
With this, you're changing only the HTMLInputElement value property, not the tag attribute.
So, was I say, this turns the code a little confunsing.
Do you know why this
function deleteInputOnClick(input){
champ = document.getElementById(input);
if(champ.value =='E-mail'){
champ.value = "";
}
}
works but this way
function deleteInputOnClick(input){
champ = document.getElementById(input).value;
if(champ=='E-mail'){
champ= "";
}
}
it doesn't ?
It's probably a stupid little error but I really don't see where it could be.
Thank's
You're not setting the value back on the element in the second way, you're just assigning it to a local variable, you still need to do document.getElementById(input).value = champ;
That is because is champ is a variable that has been assigned the value of the input element.
Changing its value will not change the value of the input (as it is not a two-way binding, you just assigned the value to it)
So you need to directly target the value property of the input to alter its value
If you are trying to avoid using the .value to a lot of places you can cache both the input element and its value for different uses..
function deleteInputOnClick(input){
var champ = document.getElementById(input),
value = champ.value;
if(value=='E-mail'){
champ.value = "";
}
}
document.getElementById(input).value returns a string value while document.getElementById(input) returns a reference (an object). So in one case only the value of the local variable is changed, in the other the original object still links to the DOM value.
Have a look at this question: Javascript by reference vs. by value
var a = document.createElement('div');
a.id = "myDiv";
and
var a = document.createElement('div').id = "myDiv";
What is the difference between them such that the first one works and the second one doesn't?
Setting the id of the element does not return the element. It returns "myDiv" actually, so the var a is getting set to "myDiv" instead of the div itself.
The second one doesn't work because the "return" value from createElement is used to set the id. As that's an assignment and not chaining, it doesn't return the reference to the new element back to "a" and thus fails.
The second doesn't work as you're creating an element but immediately performing an operation upon it. The a variable is set to the string "myDiv" instead.
foo = 'bar' as a statement actually returns a value, which is 'bar'.
a = document.createElement('div'); //this sets `a` to DOM Node
a = document.createElement('div').id = 'myDiv'; //this sets `a` to 'myDiv'
//it's the same as
document.createElement('div').id = 'myDiv';
a = 'myDiv';
Don't ever do this
If you wanted to set both the ID and the a variable in one line, you could use parens:
(a = document.createElement('div')).id = 'myDiv';
That's because a = document.createElement('div') retuns the newly created DOM Node.
If you really want a short way, you can write :
(window.a=document.createElement('div')).id="myDiv";
Fiddle : http://jsfiddle.net/F23cD/
In the first statement you put the created element of type "div" into variable "a", and then set the element property "id" of "a" to "myDiv". Then "a" is now the element.
In the second statement you:
create the element of type "div": document.createElement('div')
set the element property "id" to "myDiv" and
set "a" to "myDiv" also
Then, "a" is now "myDiv" and not the element.
// use this
a.setAttribute("id","myDiv");