如何使用jquery获取标签内的所有html? [重复]

时间:2022-09-22 15:08:00

This question already has an answer here:

这个问题在这里已有答案:

Consider this for example:

考虑这个例子:

<div>
  A&
  <br>
  B
</div>

If I use $('div').html(), it returns A&amp;<br>B. It converts A& into A&amp; which I do not want.

如果我使用$('div')。html(),则返回A&
B.它将A&转换为A&这是我不想要的。

If use use $('div').text(), it returns A&B. It ignores the <br> which I do not want either.

如果使用$('div')。text(),则返回A和B.它忽略了我不想要的那个。

I'm looking for a way to get all the html inside the div without parsing it and without skipping over the tags like <br> either.

我正在寻找一种方法来获取div中的所有html而不解析它,也没有跳过像
这样的标签。

This is the result I want: A&<br>B. How do I achieve that?

这是我想要的结果:A&
B.我如何实现这一目标?

2 个解决方案

#1


4  

function decodeEntities(encodedString) {
    var textArea = document.createElement('textarea');
    textArea.innerHTML = encodedString;
    return textArea.value;
}
console.log(decodeEntities($('div').first().html()))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  A&
  <br>
  B
</div>

EDIT

See also node.innerText https://developer.mozilla.org/en-US/docs/Web/API/Node/innerText

另请参见node.innerText https://developer.mozilla.org/en-US/docs/Web/API/Node/innerText

#2


2  

This is really a "hack" but it does work.

这真的是一个“黑客”,但确实有效。

$("<textarea>").html($("div").html()).val()

#1


4  

function decodeEntities(encodedString) {
    var textArea = document.createElement('textarea');
    textArea.innerHTML = encodedString;
    return textArea.value;
}
console.log(decodeEntities($('div').first().html()))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  A&
  <br>
  B
</div>

EDIT

See also node.innerText https://developer.mozilla.org/en-US/docs/Web/API/Node/innerText

另请参见node.innerText https://developer.mozilla.org/en-US/docs/Web/API/Node/innerText

#2


2  

This is really a "hack" but it does work.

这真的是一个“黑客”,但确实有效。

$("<textarea>").html($("div").html()).val()