Try to search your question here, if you can't find : Ask Any Question Now ?

Get Value for element – if fail get InnerHTML

HomeCategory: stackoverflowGet Value for element – if fail get InnerHTML
Avatarcraig asked 5 months ago

Basically I’m creating a chrome extension that can pull data from a webpage to speed up data entry. I’m trying to make this as easy for the users as possible, which is causing me some headache myself. I’m allowing them to put an id or a name for a field to lookup, and on my end, I have to determine if it’s an input, or just text they’re wanting pulled and see if the element exists with the id, and if not, check for an element with their provided value as a name. This has to be done with multiple fields that they provide.

I’ve tried a few iterations of code to do this. Currently I’m stuck on trying to get this code below to do the trick, but obviously it isn’t working. Is there a better way to accomplish this via javascript only?

var msg = {
  "first": "first_name_id_name",
  "last": "last_name_id_name",
  "email": "email_id_name",
  "phone": "phone_id_name"
}
var fields_to_find = JSON.parse(msg);
var data_to_push = {};
var current;
var ele;
for (var key in fields_to_find) {
  if (fields_to_find.hasOwnProperty(key)) {
    console.log(fields_to_find[key]);
    ele = document.getElementById(fields_to_find[key]);
    if (!ele.value) {
      ele = document.getElementById(fields_to_find[key]);
      if (ele.innerHTML.length == 0) {
        ele = document.getElementsByName(fields_to_find[key]);
        if (!ele.value) {
          ele = document.getElementsByName(fields_to_find[key]);
          if (ele.innerHTML.length == 0) {
            current = "";
          } else {
            current = ele.innerHTML;
          }
        } else {
          current = ele.value;
        }
      } else {
        current = ele.innerHTML;
      }
    } else {
      current = ele.value;
    }
    data_to_push[key] = current;
  }
}
console.log(data_to_push);
<input type="text" id="first_name_id_name" value="John">
<p name="last_name_id_name">Doe</p>
<input type="text" name="email_id_name" value="johndoe@example.com">
<p id="phone_id_name">123-555-1234</p>

Any help you can provide would be awesome and much appreciated.

Thanks for your time!

1 Answers
Best Answer
AvatarMannu answered 5 months ago
Your Answer

15 + 15 =

Popular Tags

WP Facebook Auto Publish Powered By : XYZScripts.com