In console.log I have an HTML object like this...
If I wanted to make a javascript to access and display the value of "name" from the HTML object (not by another method) like so...
<script type="text/javascript">
var getName = how to get it?
console.log(getName);
</script>
... how would I do it?
What if "name" was nested in something like "attributes: NamedNodeMap"? How would I get a nested value?
Use dot "." to get to all values - so if it were
Object {
anotherObject:{
Name: value
}
}
You would use var getName = Object.anotherObject.name; to get the value.
And you would have to find out the names of your objects in order to Access them.
In your case the object seems to have an _id
attribute so you can find it through that perhaps:
<script type="text/javascript">
function FindByAttributeValue(attribute, value) {
var All = document.getElementsByTagName('*');
for (var i = 0; i < All.length; i++) {
if (All[i].getAttribute(attribute) == value) { return All[i]; }
}
}
var objectToFind = FindByAttributeValue("_id","zr9Gk...");//put in the ID here
var getName = objectToFind.name;
console.log(getName);
</script>
I got the function from here.
You have many ways:
if console log shows _id and name then.
use:
alert(object.name); // For testing purpose.
alert(object._id); // For testing purpose.
if it is a selector then use:
<script type="text/javascript">
var getName = $("selector").text();
console.log(getName);
</script>
Related
I know you can SET multiple css properties like so:
$('#element').css({property: value, property: value});
But how do I GET multiple properties with CSS?
Is there any solution at all?
jquery's css method (as of 1.9) says you can pass an array of property strings and it will return an object with key/value pairs.
eg:
$( elem ).css([ 'property1', 'property2', 'property3' ]);
http://api.jquery.com/css/
Easiest way? Drop the jQuery.
var e = document.getElementById('element');
var css = e.currentStyle || getComputedStyle(e);
// now access things like css.color, css.backgroundImage, etc.
You can create your own jQuery function to do this:
//create a jQuery function named `cssGet`
$.fn.cssGet = function (propertyArray) {
//create an output variable and limit this function to finding info for only the first element passed into the function
var output = {},
self = this.eq(0);
//iterate through the properties passed into the function and add them to the output variable
for (var i = 0, len = propertyArray.length; i < len; i++) {
output[propertyArray[i]] = this.css(propertyArray[i]);
}
return output;
};
Here is a demo: http://jsfiddle.net/6qfQx/1/ (check your console log to see the output)
This function requires an array to be passed in containing the CSS properties to look-up. Usage for this would be something like:
var elementProperties = $('#my-element').cssGet(['color', 'paddingTop', 'paddingLeft']);
console.log(elementProperties.color);//this will output the `color` CSS property for the selected element
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.
I'm trying to parse something like this
{
"popular result":[
{"term":"Summer","url":"http://summer.com"},
{"term":"Autumn","url":"http://autumn.com"},
{"term":"spring","url":"http://spring.com/"},
{"term":"winter","url":"http://winter.com/"}]
}
<script type="text/javascript">
$(document).ready(function () {
$.getJSON('/Controls/GetPopularSearches', function (json) {
for (var i = 0; i < json.length; i++) {
$.each(myJson.i, function (key, value) {
alert(value.term);
});
}
});
});
</script>
but nothing happened! Because is array in array! Please let me know how to do this
Arrays and objects are different things. You will want to investigate them tons more before things get really challenging.
Assuming json really does equal the object you provide (in JSON those show up as {}), then json['popular result'] (you could use a . if there wasn't a space) is the array (in JSON those show up at []) you want to traverse.
For some reason, this confusion got you looping over an object (not going to get you anywhere as length is rarely defined for it) and then (ignoring the typo on myJson), you started looping over something that didn't exist (which didn't crash b/c it never got there).
Cleaning it up...
<script type="text/javascript">
$(document).ready(function () {
$.getJSON('/Controls/GetPopularSearches', function (json) {
for (var i=0;i<json['popular result'].length;i++) {
alert(json['popular result'][i].term + ' points to the URL ' + json['popular result'][i].url);
}
});
});
</script>
Notice how the alert references the json object (that's your variable name), the popular result array, then [i] is the "row" in that array, and the term/url element of the object on that row.
NOTE: Running something with a ton of alerts as you're debugging is annoying. Check out console.log.
You don't need $.each and you need to loop over the array set as the value of popular result which is inside a containing object.
$.getJSON('/Controls/GetPopularSearches', function (json) {
var arr = json['popular result'];
for (var i = 0, l = arr.length; i < l; i++) {
console.log(arr[i].term);
}
});
Demo.
Check this fiddle
var jsontext =
'{"popularresult":[{"term":"Summer","url":"http://summer.com"},{"term":"Summer","url":"http://summer.com"}]}';
var getContact = JSON.parse(jsontext);
for (i = 0; i < getContact.popularresult.length; i++) {
alert(getContact.popularresult[i].term);
}
http://jsfiddle.net/ae8gd/
If you get the jsonObject as shown then
var JsonArray=json.popular; //get jsonArry
$.each(JsonArray,function(i,val){
// do logic
});
To parse json use JSON.parse();
This is the code:
var groups = {
"JSON":{
"ARRAY":[
{"id":"fq432v45","name":"Don't use me."},
{"id":"qb45657s","name":"Use me."}
]
}
}
I want to get the name value where the id is "qb45657s" how could this be accomplished? I figured the obvious loop through all of the array and check if it's equal but is there an easier way?
Edit: I cannot change "Array" to an object because I need to know the length of it for a different function.
You can simply filter on the given id:
groups["JSON"]["ARRAY"].filter(function(v){ return v["id"] == "qb45657s"; });
This will return [{"id":"qb45657s","name":"Use me."}]
Assuming you had a valid JSON string like this (note I say valid, because you need an enclosing {} or [] to make it valid):
var json = '{"JSON":{
"ARRAY":[
{"id":"fq432v45","name":"Don't use me."},
{"id":"qb45657s","name":"Use me."}
]
}
}';
You would just parse it into an actual object like this:
var jsonObj = JSON.parse(json); // makes string in actual object you can work with
var jsonArray = jsonObj.JSON.ARRAY; // gets array you are interested in
And then search for it like:
var needle = 'qb45657s';
var needleName;
for (var i = 0; i < jsonArray.length; i++) {
if (jsonArray[i].id === needle) {
needleName = jsonArray[i].name;
}
}
<input id="some_id" value="some_value">
I need to create {some_id: some_value} (in other words i need to use as name of the attribute value of id) from upper input.
I tried:
jQuery('[name="page-numbers[]"]').map(function () {
return { jQuery(this).attr('id'): jQuery(this).val()};
}).get();
jQuery('[name="page-numbers[]"]').map(function () {
return {this.id: this.value};
}).get();
But every time i get an error near {this.id:. If only call this.id or this.value or same jQuery - result returns.
In your case you should use square bracket notation for defined empty object:
$('[name="page-numbers[]"]').map(function() {
var obj = {};
obj[this.id] = this.value;
return obj;
}).get();
If you want to create some sort of "input_id" : "input_value" key-value assoc, you are doing it with the wrong method, I'd say. Try this:
var assocs = {};
jQuery('[name="page-numbers[]"]').each(function () {
assocs[this.id] = this.value;
})
using .map you will get an array of many one key/value maps as a result.