Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery Add div inside h1 tag

Tags:

html

jquery

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.

like image 908
Hue Avatar asked Dec 17 '22 00:12

Hue


2 Answers

Try to use use $('h1').wrapInner('<div class="wrap" />');

But use a <span class="wrap" />

Demo jsBin

From the DOCS: http://api.jquery.com/wrapInner/

like image 193
Roko C. Buljan Avatar answered Jan 12 '23 16:01

Roko C. Buljan


<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>?

like image 38
Niet the Dark Absol Avatar answered Jan 12 '23 16:01

Niet the Dark Absol