![](/img/trans.png)
[英]Add a char to the start of each line in JavaScript using regular expression
[英]how to add a specific char at beginning of each line in div ? (javascript)
我想在html元素的每一行的開頭添加char,例如:
<div id="container">
<p>first part here !</p>
but they is text here too
<span>and bla bla bla</span>
foo
<p>bar</p>
baz
</div>
預期
<div id="container">
<p>#first part here !</p>
#but they is text here too
<span>#and bla bla bla</span>
#foo
<p>#bar</p>
#baz
</div>
渲染: https : //jsfiddle.net/wna21a1q/
我該如何使用JS(或jQuery)呢?
喜歡 :
$('#container').addAtEachLine('#')
您可以遍歷內容:
$("div").contents().each( function () { if(this.nodeType==1) { //is an element $(this).prepend(document.createTextNode("#")) } else if ($.trim(this.nodeValue).length){ //text node that is more than a return this.nodeValue = "#" + this.nodeValue; } })
span { display: block }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div> <p>first part here !</p> but they is text here too <span>and bla bla bla</span> foo <p>bar</p> baz </div>
@epascarello已經為這個問題提供了一個很好的答案。 我在玩弄它,發現了一種進一步壓縮代碼的方法。 可能不是每個人都喜歡,但是它將實際的prepend-action簡化為一行:
$("div").contents().each((i,obj)=>{ var p=['','innerHTML','','nodeValue'][obj.nodeType]; // pick method for text access var t=obj[p].trim(); // get text and remove surrounding blanks if(t.length) obj[p]='#'+t; // if text>"" prepend a "#" })
span { display: block }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div> <p>first part here !</p> but they is text here too <span>and bla bla bla</span> foo <p>bar</p> baz </div>
這是我的vanilla.js版本。
var el = document.querySelector('div'); function addchar(item) { var childNodes = item.childNodes; var countNode = childNodes.length; for (var i = 0; i < countNode; i++) { if (childNodes[i].nodeType !== 3) { addchar(childNodes[i]); } else { if (childNodes[i].nodeValue.trim()) { childNodes[i].nodeValue = "# " + childNodes[i].nodeValue; } } } } addchar(el);
span {display:block}
<div> <p>first part here !</p> but they is text here too <span>and bla bla bla</span> foo <p>bar</p> baz </div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.