Reputation: 471
Using jquery, How would I wrap a div class around the text inside all h1 tags. E.g to make all
<h1> test </h1>
in a document into
<h1> <div class="wrap">test </div></h1>
.
I am having a mental block. Any help would be much appreciated.
Upvotes: 4
Views: 11593
Reputation: 324750
<div>
is not valid inside of <h1>
. You would be better off using a <span>
. Pure JavaScript:
var h = document.getElementsByTagName('h1')[0],
d = document.createElement('span');
while(h.firstChild) d.appendChild(h.firstChild);
h.appendChild(d);
d.className = "wrap";
But that said, can't you just apply the "wrap" class to the <h1>
?
Upvotes: 6
Reputation: 7426
// Get and wrap the content from the h1
var content = $('h1').html();
content = '<div class="wrap">' + content + '</div>';
// Reinsert the content into the h1
$('h1').html( content );
This can of course be done in a single line, but this made it a bit more clear.
Upvotes: 0
Reputation: 206459
Try to use use $('h1').wrapInner('<div class="wrap" />');
But use a <span class="wrap" />
From the DOCS: http://api.jquery.com/wrapInner/
Upvotes: 6