[英]convert <a> text string to dom element with jQuery
如何將鏈接中的文本轉換為html元素?
我用
它返回值,但我無法將元素添加到其中。 $('a').text();
我已經試過了:
var someText = $('a').text();
var theElement = $('< p >' + someText + '< /p >');
someText.replaceWith(theElement);
我知道這可能會在鏈接內添加一個文本元素,這不是最佳實踐,但甚至行不通。
我真正需要的是刪除整個文本,並在將de link作為文本元素后立即將其重寫。
任何幫助表示贊賞。 謝謝
標記:
<li>
<a href="/"> <img src="image.png"> text to be converted to element </a>
</li>
我想要的是:
<li>
<a href="/"> <img src="image.png"></a>
<p> text to be converted to element </p>
</li>
由於someText
是字符串,而不是jQuery元素,因此無法在其上調用.replaceWith()
。 嘗試這樣的事情:
var someLink = $('a');
var someText = someLink.text();
var theElement = $('<p>' + someText + '</p>'); // no spaces inside tags
someLink.replaceWith(theElement);
更新由於您在問題中添加了新信息,因此可以滿足您的需求:
var someLink = $('a');
var someText = someLink.text();
var someImg = someLink.find('img');
var theElement = $('<p>' + someText + '</p>');
someLink.html(someImg).after(theElement);
http://jsfiddle.net/cvgbqb8b/2/
var anchor = $('li a');
anchor.after('<p>' + anchor.text() + '</p>')
.contents()
.filter(function(){
return (this.nodeType == 3);
})
.remove();
在此處找到用於刪除文本的代碼https://stackoverflow.com/a/17852238/1415091
我建議:
// iterate over each of the <a> elements within <li> elements:
$('li a').each(function() {
// create a <p> element, setting its text
// to that of the 'this' element (the <a>):
$('<p>', {
'text': this.textContent
// insert that created <p> after the current <a> element:
}).insertAfter(this);
// filtering the childNodes of the current <a>:
$(this).contents().filter(function() {
// keeping only those that are of nodeType === 3
// and therefore are textNodes:
return this.nodeType === 3;
// removing those nodes:
}).remove();
});
$('li a').each(function() { $('<p>', { 'text': this.textContent }).insertAfter(this); $(this).contents().filter(function() { return this.nodeType === 3; }).remove(); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul> <li> <a href="/"> <img src="http://lorempixel.com/300/300/people" />text to be converted to element</a> </li> </ul>
參考文獻:
contents()
。 each()
。 filter()
。 wrap()
。 使用.html()
var someText = 'Hey!';
$('#test').html('<p>' + someText + '</p>');
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.