0

I'm trying to get the href of <span id="username"> from another page on my website.

The jQuery:

var fetchedInfo;
$.get("./profile", function(res) {
   fetchedInfo = $(res).find("span#username").attr("href");
   alert(fetchedInfo);
});

HTML:

<div class="linkdiv">
    <span class="profile" id="username">
        <a href="https://example.com">text</a>
    </span>
</div>

Every answer I've tried from StackOverflow has resulted in a blank Alert. I'm not sure if there's something way deeper going on from my end of things or if it's still (hopefully) a fixable code issue...

Thank you for any help.

MauriceNino
  • 6,214
  • 1
  • 23
  • 60
m0a
  • 1,005
  • 2
  • 15
  • 29

1 Answers1

1

The span does not have a href attribute, but the a tag inside it has. You need to include the a tag in the find(...):

var fetchedInfo;
$.get("./profile", function(res) {
   fetchedInfo = $(res).find("span#username a").attr("href");
   alert(fetchedInfo);
});

Also, I would recommend you to test your stuff with console.log(...) like so to see what each step really does. That way you know which step fails.

var fetchedInfo;
$.get("./profile", function(res) {
   console.log($(res));
   console.log($(res).find("span#username a"));
   console.log($(res).find("span#username a").attr("href"));
   fetchedInfo = $(res).find("span#username a").attr("href");
   alert(fetchedInfo);
});

MauriceNino
  • 6,214
  • 1
  • 23
  • 60
  • Even though this is probably the technical answer it actually comes up `Undefined` now. Not sure why it changed from blank to undefined. . It's probably something wrong with the way I did the other code at this point. if you have ideas please let me know. I've been spending a while on this. – m0a Jul 21 '20 at 10:50
  • do some debugging and if you have more info, I can maybe help you. What does `console.log(res)` print? and `console.log($(res))`? and and `console.log($(res).find("span#username a"))`? @m0a – MauriceNino Jul 21 '20 at 11:30
  • Thank you . `console.log($(res))` returned undefined. `console.log(res)` did return the correct info. Then `fetchedInfo = ((res).find("span#username a").attr("href"));` returns a new error- "res.find is not a function". So this is really close! – m0a Jul 21 '20 at 13:19
  • what does `console.log(res)` print? the html text? – MauriceNino Jul 21 '20 at 17:15
  • OK, after observing the actual HTML that got printed, I see what's happening but don't get why or how to deal with it. The HTML is not pulling the particular div that I'm trying to pull data from, probably because I create that page's div via JS-- it's not a static part of the HTML. – m0a Jul 21 '20 at 21:13
  • maybe this helps? https://stackoverflow.com/questions/13413399/find-element-at-html-string @m0a – MauriceNino Jul 22 '20 at 08:41