简体   繁体   中英

href returns undefined with .attr(), .prop(), .each() etc but is able to return the value

const results = $(".someclass")
    .map((index, element) => {
        const hrefValue = $(element).find("a").prop("href");
        // or...
        const hrefValue2 = $(element).find("a").attr("href");
      
        return { hrefValue };
    })
    .get();
    console.log(results);

console log gives me what I expect. (The value of the property href ). eg https://www.google.com

But if I try to modify the href value (which, according to type of, is a 'string') with any string methods, for example

const hrefValue = $(element).find("a").prop("href").toUpperCase();

I get the error: TypeError: Cannot read property 'toUpperCase' of undefined

Everything I have researched points to jquery returning undefined, but that's not the case here I don't think, because I do get the value returned. I am just unable to modify it along the way with string methods, and that is the part I am unsure of, as to why.

EDIT: It is puppeteer so it is scraping, but here is the gist of the HTML:

<div className="someclass">
    <a href="https://www.google.com>google</a>
</div>

I am able to return the value, and the type of is 'string', but if I try to modify it with string methods, I get the undefined error.

SOLUTION: credit to @epascarello for the solution. The first object in a scraped puppeteer array is indeed blank. That is why it was giving the undefined error.

Once I placed a `.slice(1) in front of the.map(), then the results displayed properly in the console without the undefined error.

SOLUTION: credit to @epascarello for the solution. The first object in a scraped puppeteer array is indeed blank. That is why it was giving the undefined error.

Once I placed a `.slice(1) in front of the.map(), then the results displayed properly in the console without the undefined error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM