转换<a>使用jQuery将文本字符串转换为dom元素

convert <a> text string to dom element with jQuery

本文关键字:转换 字符串 dom 文本 元素 使用 lt gt jQuery      更新时间:2023-09-26

如何将链接中的文本转换为html元素?

我用 $('a').text();来定位文本,它返回值,但我无法向其中添加元素。

我试过这个:

var someText = $('a').text();
var theElement = $('< p >' + someText + '< /p >');
someText.replaceWith(theElement);

我知道这应该会在链接中添加一个文本元素,这不是最佳实践,但甚至不起作用。

我真正需要的是删除整个文本,并在取消链接后立即将其重写为文本元素。

任何帮助都将不胜感激。谢谢

标记:

<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);

http://jsfiddle.net/0xxrL6zy/


更新由于您在问题中添加了新信息,以下是满足您需求的解决方案:

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/mblase75/mzbtr0qp/1/

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>

参考文献:

  • JavaScript:
    • Node.nodeType
    • Node.textContent
  • jQuery:
    • contents()
    • each()
    • filter()
    • wrap()

使用.html()

var someText = 'Hey!';
$('#test').html('<p>' + someText + '</p>');

Fiddle:http://jsfiddle.net/howderek/3t3Lw75x/