[英]Jquery Add div inside h1 tag
Using jquery, How would I wrap a div class around the text inside all h1 tags. 使用jquery,我如何在所有h1标签内的文本周围包装div类。 Eg to make all
例如,做所有
<h1> test </h1>
in a document into 在一份文件中
<h1> <div class="wrap">test </div></h1>
. <h1> <div class="wrap">test </div></h1>
。
I am having a mental block. 我有精神障碍。 Any help would be much appreciated.
任何帮助将非常感激。
Try to use use $('h1').wrapInner('<div class="wrap" />');
尝试使用
$('h1').wrapInner('<div class="wrap" />');
But use a <span class="wrap" />
但是使用
<span class="wrap" />
From the DOCS: http://api.jquery.com/wrapInner/ 来自DOCS: http : //api.jquery.com/wrapInner/
<div>
is not valid inside of <h1>
. <div>
在<h1>
内无效。 You would be better off using a <span>
. 你最好使用
<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”类应用于
<h1>
吗?
// 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. 这当然可以在一行中完成,但这使它更加清晰。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.