0

How to get link href value?

import $ from "jQuery";

const page = `<!DOCTYPE html>
<html>
<head>
                <link rel='up' href='123' />
    </head>
    <body></body>
</html>`;

const $theme = $(page);
console.log($theme.find(`link[rel='up']`).attr("href")); // undefined

Codesandbox.

I read that browser may get rid of head elements when parsed from string. Is it the case? Do i really need to use regexp?

UPDATE: In real code it's used like this inside chrome extension background script:

$.get(`link`, (theme) => {
      const $theme = $(theme)
      const publishedAt = $theme.find('.published').first().attr('title')
})

And it's works fine for any element inside body. I'm not sure why it's not working even for body in sandbox...

ZiiMakc
  • 31,187
  • 24
  • 65
  • 105
  • I have been playing around with this and honestly dont know what are you doing, but you are getting array out of $theme not a string. And find searchers for DOM elements, like I said, i dont know what are you doing or trying to accomplish. Add console.log($theme); I tried to convert it into string but had no luck with your final code row. – ikiK Jun 06 '20 at 16:44
  • @ikiK i load page using .get, then convert it to jqery and search some data. – ZiiMakc Jun 06 '20 at 16:50
  • Well find is searching for DOM elements, you need to get string and use index of on it or something like that. I dont think find will work like that on a string or array in your case. Seems wrong. But im no expert. – ikiK Jun 06 '20 at 16:52
  • @ikiK it's works for all elements in body, i have only problems with head. – ZiiMakc Jun 06 '20 at 16:55
  • https://stackoverflow.com/questions/3592475/how-to-get-head-content-of-the-current-page-with-jquery-or-js – ikiK Jun 06 '20 at 16:57
  • @ikiK thank but i want to know what is the problem about. – ZiiMakc Jun 06 '20 at 16:58
  • if you had hard coded head in your html snippet example it shouldn't be a problem as it seems. But you have arrays in code provided above. Sorry im just trying to get my head around this. – ikiK Jun 06 '20 at 16:58
  • @ikiK i have no idea what are you talking about – ZiiMakc Jun 06 '20 at 16:59
  • @RTW hi, you have said that it worked for all elements in body. By that do you mean from the index.html body or from the const page? – Achuth Varghese Jun 06 '20 at 17:11
  • @AchuthVarghese From this: $.get(`link`, (theme) => { const $theme = $(theme)}). So const, yes. – ZiiMakc Jun 06 '20 at 17:14
  • try parsing the string to html. By playing in sandbox code you have provided I find that an input field was found using find() but not a div. Also, if you console log just the `$theme.find('#demo')` you can see that you will get an object with length 0. – Achuth Varghese Jun 06 '20 at 17:45

0 Answers0