1

Wondering how can i find the 'link' element inside the HEAD tag from variable 'x' using Jquery?

Tried, but below code is not working.

var x = "<html><head> <link> I'm inside head tag </link> </head></html>";

var y = $('<div>' + x + '</div>');

y.find('head')[0].html();

alert(y);
Lipak
  • 33
  • 1
  • 7

2 Answers2

0

Get innerHTML property since index 0 returns DOM object or directly apply html() method on jQuery object.

Although you can't directly parse the HTML string which contains HEAD or BODY tags(which would avoid those elements since it can't be a child of a div element) so you need to treat it as XML. To parse XML use $.parseXML() the result would be an array of nodes, now converts into jQuery object by simply wrapping using jQuery and do the rest.

var x = "<html><head> <link> I'm inside head tag </link> </head><body></body></html>";

// parse the string as XML and generate XML document
// and wrap using jQuery to generate jQuery object from it
var y = $($.parseXML(x));

// get DOM object by index and get html content
var a = y.find('head')[0].innerHTML;
// or use jQuery method to get content
var b = y.find('head').html();

console.log(a, b)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>


Refer : Parsing of html string using jquery
Community
  • 1
  • 1
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
0

If you need to find the link(s) from the document header, you can use this selector

$('head link')

However, if you need to find the link element(s) inside the header from a variable, you can do this

var x = "<html><head> <link> I'm inside head tag </link> </head></html>";
$(x).filter( function (i,a){ return $(a).is('link');});
Anthony C
  • 2,117
  • 2
  • 15
  • 26