Jquery在h1标签中添加div

时间:2022-11-03 10:06:54

Using jquery, How would I wrap a div class around the text inside all h1 tags. E.g to make all

使用jquery,如何在所有h1标记中围绕文本包装一个div类。E。g让所有

<h1> test </h1>

<标题> < / h1 >测试

in a document into

在一个文档

<h1> <div class="wrap">test </div></h1>.

<标题> < div class = " wrap " > < / div > < / h1 >测试。

I am having a mental block. Any help would be much appreciated.

我有心理障碍。非常感谢您的帮助。

3 个解决方案

#1


6  

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

尝试使用$('h1')。wrapInner(“< div class = "包装" / > ');

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

但是使用

Demo jsBin

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

从文档:http://api.jquery.com/wrapInner/

#2


6  

<div> is not valid inside of <h1>. You would be better off using a <span>. Pure JavaScript:

中无效。您最好使用。纯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>?

但也就是说,你不能将“wrap”类应用到

吗?

#3


0  

// 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.

当然,这可以在一行中完成,但这使它更加清晰。

#1


6  

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

尝试使用$('h1')。wrapInner(“< div class = "包装" / > ');

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

但是使用

Demo jsBin

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

从文档:http://api.jquery.com/wrapInner/

#2


6  

<div> is not valid inside of <h1>. You would be better off using a <span>. Pure JavaScript:

中无效。您最好使用。纯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>?

但也就是说,你不能将“wrap”类应用到

吗?

#3


0  

// 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.

当然,这可以在一行中完成,但这使它更加清晰。

相关文章