Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert html text to jquery object

Tags:

html

jquery

I would need to transform text to html jquery object, so that I had an access to the values specified in the and the following example.

var htmlContent = '<!doctype><html><head><title>Lorem Ipsum</title>Other code</head><body><div id="content"><h1>Custom code</h1><h2>Highlight2</h2></div></body></html>';

I want to modify so that I could work with HTML content in jquery follows

htmlContent.find('head title').text();

to h1 and h2 know approaches, probably because they are not vnotrene tags in <div id="content"></div>

Currently I have the following code:

var htmlContent = $(htmlContent);

But it does not work properly.

Thank you for counseling.

like image 858
user3061527 Avatar asked Aug 28 '26 07:08

user3061527


2 Answers

I would propose next:

var htmlContent = '<!doctype><html><head><title>Lorem Ipsum</title>Other code</head><body>Custom code</body></html>';

// use temporary iframe
var iframe = document.createElement('iframe');
document.body.appendChild(iframe);
iframe.contentDocument.write(htmlContent);

// get <title> content; next should work in IE8 too
var titleText = iframe.contentDocument.querySelector('head title').innerHTML;
console.log(titleText);

// remove temporary iframe element
document.body.removeChild(iframe);

Note: I've changed .textContent to .innerHTML for IE8 support.

Alternative way, using jQuery:

var iframe = $('<iframe>').appendTo('body');
iframe[0].contentDocument.write(htmlContent);
var titleText = $('head title', iframe[0].contentDocument).text();
console.log(titleText);
iframe.remove();
like image 141
Rost Avatar answered Aug 29 '26 21:08

Rost


Your code seem ok, this is the way how to create new elements in jQuery, eg.:

var $a = $('<div id="main"><p><strong>hello</strong><p></div>');

$a.find('p strong').text();

-> "hello"

I think the problem is with the html/head tags instead, jQuery ignores them, but I guess you don't need the whole html block anyway:

$('<html><head><div></head></html>');

-> [<div>​</div>​]

If you are parsing a string that contains a complete html I'd recommend using jQuery.parseHTML(), or if you need the body node too, you can use documentFragments or iframe, in this case there's no problem with <html> nodes.

var htmltext = "<html><div><p>test</p></div></hmtl>"
$('<div>').append($.parseHTML(htmltext)).find('p').text()

-> "test"

References:

  • http://api.jquery.com/jQuery/#creating-new-elements

  • https://developer.mozilla.org/en-US/docs/Web/API/document.createDocumentFragment

like image 38
Andras P Avatar answered Aug 29 '26 20:08

Andras P