Teja
Teja

Reputation: 133

Jquery: Get Head and Body Tag Contents from string

I am having a string like below:

<head>
    This is the Head
</head>
<body>
    <div>
        <div>
            <p> Body Content <br /></p>
            <p>&nbsp; Hello World <br /></p>
        </div>
    </div>
</body>

It is having both head and body tags. Now I want the contents of head tag and body tag using jquery. Can anyone help?

Upvotes: 1

Views: 3872

Answers (4)

user3620693
user3620693

Reputation: 53

Well suppose your string variable is "s" so the code is:

var html = document.createElement('html');
html.innerHTML = s;

var head = $(html).find('head:first');
var body = $(html).find('body:first');

Upvotes: 3

Yogesh Gupta
Yogesh Gupta

Reputation: 36

You can use the regular expression as well, with basic and simple and one more benefit of using that is you can get any other html as well. Please find the code below :

var html = '<head>\
    This is the Head\
</head>\
<body>\
    <div>\
        <div>\
            <p> Body Content <br /></p>\
            <p>&nbsp; Hello World <br /></p>\
        </div>\
    </div>\
</body>';
    
var reg = /\<head[^>]*\>([^]*)\<\/head/m;
var head = html.match( reg )[1];

var reg2 = /\<body[^>]*\>([^]*)\<\/body/m;
var body = html.match( reg2 )[1];

document.getElementById("Head").innerHTML = head;
document.getElementById("body").innerHTML = body;
.head{
  border:1px solid red;  
}
.body{
  border:1px solid red;  
}
<div class="head">
<h1>
Heading
</h1><br />
<div id="Head">
</div>
</div> <br />
<div class="body">
<h1>
Body
</h1> <br />
<div id="body">
</div>
</div>

Upvotes: 0

Jim
Jim

Reputation: 16002

have you considered trying these jquery expressions.

$('head').html();
$('body').html();

for combined text the following jquery expressions.

$('head').text();
$('body').text();

Upvotes: -1

Krishna9960
Krishna9960

Reputation: 529

Here parse the string to html object and then you will be able to access the elements.

Here is code for the same

var str = "<head>This is the Head</head><body><div><div><p> Body Content <br /> </p><p>&nbsp; Hello World <br /></p> </div></div></body>";


//This will parse the string to HTML
var htmlString = $.parseHTML(str);

//To get the Body content
console.log(htmlString[1].innerHTML);

//To get the HTML Tag Content
console.log(htmlString[0].data);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Upvotes: 0

Related Questions