0

In console.log I have an HTML object like this...

enter image description here

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?

Deborah
  • 4,316
  • 8
  • 31
  • 45

2 Answers2

1

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.

Community
  • 1
  • 1
Cold_Class
  • 3,214
  • 4
  • 39
  • 82
  • The actual HTML is loaded dynamically from a Mongo db, so I wouldn't be able to create a script with a static _id. (I asked another question about how to get the Mongo db field value in a similar script, but it seemed like it would be useful to know how to get it from the object as well). The first part of your answer set me on the right track - thanks! – Deborah Jul 17 '16 at 11:02
1

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>
Manjuboyz
  • 6,978
  • 3
  • 21
  • 43
  • So if I do this, "var myValue = (object.name);" console.log writes, "object is not defined". – Deborah Jul 17 '16 at 10:47
  • it is clearly saying its not defined, would you mind sharing your code ? so that we can try to fix this. – Manjuboyz Jul 17 '16 at 10:48
  • my bad. Your answer does work for the question's object. In my real case, the object is actually being delivered from a Mongo db collection and is much more complex with all kinds of nested values with colons and brackets everywhere. I tried it on my real case and got "undefined". It's 4 a.m. where I am :) – Deborah Jul 17 '16 at 11:19
  • it will be difficult for us to give suggestion without seeing the code base!. – Manjuboyz Jul 17 '16 at 11:32