I'm working on my first JavaScript game and I want to display certain attributes inside of < p> tags. The ID of each < p> tag will be equal to "show-" and the name of the attribute (see example below for the attribute "name").
But I'm having trouble getting the syntax right for getElementById. Any suggestions?
<p id="show-name"></p>
<script>
name = "Bob";
function display(attribute) {
putItHere = "'show-"+attribute+"'"
document.getElementById(putItHere).innerHTML = attribute;
}
display(name);
</script>
You need to target the right element. Currently you are targeting 'show-Bob' and not 'show-name' what your trying to do. So first generate the id, from the key name and then assign a value to that element.
var name = "Bob";
function display(key, value) {
var putItHere = "show-"+ key;
document.getElementById(putItHere).innerHTML = value;
}
display('name', name);
note keep in mind that IDs should be unique within the document
However, other way to do that is to target all elements with a specific tag, for instance
<div data-id="name"></div>
<div data-id="name"></div>
<div data-id="name"></div>
<script type="text/javascript">
var name = "Bob";
function display(key, value) {
var putItHere = "show-"+ key;
var elements = document.querySelectorAll('div[data-id="'+key+'"]');
for(var eid in elements) {
var element = elements[eid];
element.innerHTML = value;
}
}
display('name', name);
</script>
note that that this doesn't work in IE7 and below.
Your attribute is Bob. So putItHere = "'show-"+attribute+"'" is equivalent to: putItHere = "'show-"+"Bob"+"'", which makes no sense.
You should get the following error Uncaught TypeError: Cannot set property 'innerHTML' of null.
This should do:
function display(attrname, val){
document.querySelector('#show-'+attrname).innerText=val;
}
display("name","Bob");
Here is the Fiddle to play with.
Related
I know that the title sounds weird but I don´t know how to exactly describe my problem. I have an array with all the divs id I created before. Now I want to take the first div´s id and remove the div by parentNode.removeChild(); The console prints:
'The "removeChild" property of an undefined or null reference can not be retrieved.'
I hope you can help me with that :)
var animation_time = 1500;
var div_id_selection = [];//it contains 'div0', div1, div2 ... divn
var array_counter = -1;
// Before that is a function that creates a div by document.createElement("div); with the id div0, div1, div2 ...than it writes the id into the array:
div_id_selection.push('div' + id);
var delete_divs = function(){
setTimeout(function(){
array_counter += 1;
var div_to_delete = div_id_selection[array_counter];
//var div_to_delete_str = div_to_delete.toString(); I already tried it with the string-didn´t work
console.log(div_to_delete);
console.log(array_counter);
div_to_delete.parentNode.removeChild(div_to_delete); // here is the problem
}, animation_time);
}
div_to_delete is a string ( id that is stored in the array ).
parentNode method is only available on a DOM object.
You will have to first select the element using the id.
// get the correct DOM object using the array
var elem = document.getElementById(div_to_delete);
elem.parentNode.removeChild(elem);
I need to pass a value from html and use it to find a var in my Js, so according to the value in theId on my html I could use the var in my js. How can I do that?
HTML
<input id="Waist" type="checkbox" onchange="getToWork(this.id)" >Waist
<script> tag on HTML
function getToWork(theId){
usedCheckBox(theId);
}
myJs.js
function usedCheckBox(theId){
var temp1 = theId.name; - will be undefined
var temp2 = Waist.name; - will work
}
var Waist = {name:"bob",age:"17"}
The problem with your code is, you are not using document.getElementById as below:
JS:
document.getElementById("Waist").addEventListener("change",function(evt){
getToWork(this.id);
})
function getToWork(theId){
usedCheckBox(theId);
}
function usedCheckBox(theId){
console.log(theId);
console.log(Waist);
var temp1 = document.getElementById("Waist").val; // will return Waist
var temp2 = Waist.val(); // generate error, don't know what you want
}
var Waist = "change today!"
Fiddle:
https://jsfiddle.net/xLvzah8w/1/
I understood your question now and for that you should create one parent object as shown:
function usedCheckBox(theId){
var temp1 = parent[theId].name; // will return bob
console.log(temp1);
var temp2 = parent.Waist.name; // will return bob
console.log(temp2);
}
var parent = {
Waist : {name:"bob",age:"17"}
}
The reason why your code doesn't work is because you are trying to access property of a string. 'theId' is a string with value 'Waist' where Waist is an object so error occurs.
Updated fiddle: https://jsfiddle.net/xLvzah8w/2/
The correct way to proceed with this is:
In place of var temp1 = theId.val();
Use document.getElementById(theId).value
When you do: theId.val(), it makes sense that it's undefined. Calling getToWork(this.id) is sending a string, not an HTML element. Therefore calling .val() on a string is undefined.
If you're trying to get the text value stored in the checkbox element that was pressed, you need to change to ...
function getToWork(arg) {
console.log(document.getElementById(arg).value);
}
<input id="Waist" type="checkbox" value="INPUT_BOX" onchange="getToWork(this.id)"> Waist
You should avoid using the onclick attribute and rather listen for the event "js side" (addEventListener/attachEvent).
In the context of those eventhandlers, this generally represents the element the event listener has been attached to:
document.getElementById("Waist").addEventListener("change",getToWork);
function getToWork(){
usedCheckBox(this);
}
function usedCheckBox(elem){
var value = elem.value ;
}
I am creating an object that stores various elements and their CSS properties.
The code I have now:
// My object
var cssStorage = {};
function store(element, cssProperty, value) {
// Initialize the (sub-)objects if they don't exist
cssStorage[element.id] = cssStorage[element] || {};
cssStorage[element.id][cssProperty] = cssStorage[element][cssProperty] || {};
// Set the cssProperty to equal the value
cssStorage[element.id][cssProperty] = value;
};
Example:
// My element
var box = document.getElementById("box");
// Let's call the function twice to save to properties
store(box, "display", "block");
store(box, "height", "74px");
Now my Object is populated like so:
cssStorage = {
box: { // <- box is the id of the HTML element <div id = "box"></div>
// The property-value pairs
display: "block",
height: "74px"
}
};
So now, if I type the code in the console:
return cssStorage.box.display; // Returns "block"
As you saw in the first block of code I posted, I used element.id as the element's unique identifier, to be able to use it as shown right above.
My problem is the dependency of my script upon element.id. Some elements of my DOM don't have an id and therefore the function is useless for these elements.
In essence, what I want to achieve is to call the function store when my element doesn't have an ID as follows:
// Some ways to get an element
var box = document.getElementsByClassName("boxes")[0];
var box = document.getElementsByTagName("div")[0];
var box = document.getElementsByName("jack")[0];
// It'll show an error, as the function uses 'element.id' and my element doesn't have one
store(box, "display", "block");
Is there a unique identifier for every node in the DOM?
Something that I could use as the name of:
cssStorage = {
[THE NAME]: {}
};
If not, how can I create a unique identifier for my elements, so that I can use the function as shown above without needing an id, class or other property that my element may not have?
You can easily coin a unique identifier for any element that doesn't yet have one:
var customIDprefix = "__myCustomPrefix__";
var customIDcntr = 0;
function getNextID() {
return customIDprefix + customIDCntr++;
}
And, then you can make sure any element you're using has a unique ID:
function checkID(elem) {
if (!elem.id) {
elem.id = getNextID();
}
}
If you're using ES6, you can also just use a WeakMap or Map object as your CSSStorage mechanism which let the DOM element itself be the key so you don't have to make a string key.
In that case, you'd just do this:
var cssStorage = new Map();
cssStorage[elem] = { // <- elem (your DOM element itself) becomes your key into the cssStorage
// The property-value pairs
display: "block",
height: "74px"
}
You could use an integer to handle a sequence and set the id to elements that does not have it, prefixing to avoid duplicates (for example 'myid' + idSequence++).
Please check if this works. Basically trying to clone the original element and assign it back to the original after adding id with random generator.
function store(element, cssProperty, value) {
if ( element.id == undefined ) {
var clonedElem = element.cloneNode(true);
clonedElem.id = Math.floor((Math.random() * 1000) + 1);
element = clonedElem;
}
// Initialize the (sub-)objects if they don't exist
cssStorage.[element.id] = cssStorage[element] || {};
cssStorage.[element.id][cssProperty] = cssStorage.[element][cssProperty] || {};
// Set the cssProperty to equal the value
cssStorage.[element.id][cssProperty] = value;
};
Inside of a jQuery click event listener I have some code like this:
function (evt) {
evt.preventDefault();
var reportbox = $(this).closest('.activityItem');
var id = reportbox.data('questionId');
...
}
This works fine for data-question-id attributes, but I'm generalizing the function now and I need to grab the value from any of the following:
data-question-id
data-answer-id
data-comment-id
data-user-id
data-company-id
What's the best way to do this?
If you know only one of those attributes will be present and you want to retrieve that single value you can use this:
var element = $(el);
var dataAttrs = ['question-id', 'answer-id', 'comment-id', 'user-id', 'company-id'];
var data = getUnknownAttr(element, dataAttrs);
function getUnknownAttr(element, potentialAttrs) {
var $element = element instanceof $ ? element : $(element);
var result = null;
potentialAttrs.forEach(function (attr) {
var temp = $element.data(attr);
if (typeof temp !== 'undefined') {
result = temp;
}
});
return result;
}
As Brian points out, you could access the dataset property to retrieve all the element's data-* attributes:
$('.activityItem').each(function () {
var dataAttributes = this.dataset;
Object.keys(dataAttributes).forEach(function (key) {
console.log(key, dataAttributes[key]); // key, value
});
});
Since you only want the first data attribute, you could simply use:
var dataAttributes = this.dataset;
var id = dataAttributes[Object.keys(dataAttributes)[0]];
It's important to note that the dataset property returns the attribute names in camel case without the data prefix. In other words, data-question-id would be questionId.
If you want to retrieve all of an element's attributes, access the attributes property and check which attributes start with data-* and end with -id. It's definitely more verbose, but it may work better in other scenarios.
$('.activityItem').each(function () {
var attributes = this.attributes;
Object.keys(attributes).forEach(function (key) {
var attribute = attributes[key];
if (/^data-.*-id$/.test(attribute.name)) {
console.log(attribute.name, attribute.value);
}
})
});
I just thought of what I was looking for. I guess my question confused you, but here's what I wanted:
$('#test').children().each(function () {
var reportbox = $(this);
var id = reportbox.data(Object.keys(reportbox.data())[0]);
reportbox.text(id);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test">
<div data-question-id="1"></div>
<div data-answer-id="2"></div>
<div data-comment-id="3"></div>
<div data-user-id="4"></div>
<div data-company-id="5"></div>
</div>
The line of focus being:
var id = reportbox.data(Object.keys(reportbox.data())[0]);
Edit
Alternatively thanks to #Brian's comment I can rewrite this to:
var id = this.dataset(Object.keys(this.dataset)[0]);
I have a question regarding Javascript array.
I have the following javascript array:
var startTimeList= new Array();
I've put some values in it. Now I have the following input (hidden type):
<input type="hidden" value"startTimeList[0]" name="startTime1" />
Hoewever, this is obviously not correct because the javascript array is not recognized in the input hidden type. So I cant even get one value.
Does anyone know how I can get a value in the input type from a javascript array?
You need to set the value in Javascript:
document.getElementById(...).value = startTimeList[0];
Use this :
<script>
window.onload = function() {
document.getElementsByName("startTime1")[0].value = startTimeList[0];
}
</script>
You have to set value from javascript.
Something like document.getElementById (ID).value = startTimeList[0];
You execute javascript from body oload event.
You need to set the value through JavaScript itself so.
document.getElementById("startTime1").value = startTimeList[0];
Or JQuery
$("#startTime1").val(startTimeList[0]);
Assign "startTime1" as the id above.
You can find your element by name with:
document.getElementsByName(name)[index].value = 'new value';
OR
You should identify your element and then change the value;
Give your element an ID for example id="ex"
Get the element with JavaScript(of course once the DOM is ready) with var element = document.getElementById('ex')
Change the value with element.value = 'your value';
You'd need to split the array into a delimited string and then assign that string to the value of the hidden input.
Then, on postback or similar events you'd want to parse the value back into an array for use in JavaScript:
var startTimeList = [1,2,3,4,5];
var splitList = '';
for(var i = 0; i < startTimeList.length; i++)
{
splitList += startTimeList[i] + '|';
}
and back again:
var splitList = '2|4|6|8|';
var startTimeList = splitList.split('|');