[英]Add a span tag inside a h5 using javascript
我想在此h5標簽內插入一個使用javascript的類的跨度,這將適用於第一個單詞:
<div class="container_skitter" style="width: 715px; height: 230px;">
<div class="image">
<a href="#">
<div class="label_skitter" style="width: 715px; display: block;">
<h5>Increase knife life</h5>
</div>
</div>
</div>
后
<div class="container_skitter" style="width: 715px; height: 230px;">
<div class="image">
<a href="#">
<div class="label_skitter" style="width: 715px; display: block;">
<h5><span class="firstword">Increase</span> knife life</h5>
</div>
</div>
</div>
是這樣嗎
<script>
$('h5').html(function (i, html) {
return html.replace(/(\w+\s\w+)/, '<span>$1</span>')
});
</script>
似乎無法使其正常工作。
謝謝
將此添加到document.ready下。 您的腳本在完全加載DOM之前運行太早。 另外,您只需要匹配第一個單詞,這樣就足以選擇它。 /(\\w+\\s)/
$(document).ready(function(){
$('h5').html(function (i, html) {
return html.replace(/(\w+\s)/, '<span class="test">$1</span>')
});
});
您走在正確的軌道上。 讓我們嘗試在沒有JQuery的情況下執行此操作!
<script>
Array.prototype.slice.call (document.querySelectorAll ('h5')).forEach
function (h5el) {
// we will come here with h5el referencing an h5 of the document
h5el.innerHTML = h5el.innerHTML.replace (/^(\w+)\s/,
'<span class="firstword">$1</span> ';
});
</script>
將此腳本放在標記和presto之前或之后,所有h5
元素都會被修改。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.