简体   繁体   English

使用Javascript突出显示HTML中的文本后,如何获取包含HTML元素的字符串?

[英]How can i get the string including HTML element after highlighting the text in HTML using Javascript?

Say, I highlighted this text The Title is Superman and Batman in my page. 说,我在页面中突出显示了该文本The Title is Superman and Batman

How can i get the text including it's HTML element? 如何获取包含HTML元素的文本?

Based on my example, I should get this: 根据我的示例,我应该得到以下信息:

The Title is <i>Superman</i> and <i>Batman</i>

Use jquery html selector to get the value with HTML selector. 使用jquery html选择器通过HTML选择器获取值。

HTML: HTML:

 <div id="test">this is my <i>test</i></div>

JS: JS:

 $('#test').html()

You should take the values adding a class or id. 您应该采用添加类或ID的值。

HTML: HTML:

<div class="test"><i>Superman</i></div>
<div class="test"><i>Batman</i></div>

JS: JS:

$('.test').html()

Live Example 现场例子

Since everyone is requiring OP to use jQuery, here's the native JS equivalent. 由于每个人都要求OP使用jQuery,因此这是本地JS等效项。 You can select the html content of an element like so : 您可以选择元素的html内容,如下所示:

var html = document.getElementById('text-container').innerHTML;

You might want to redisplay all the HTML from the container as different values, eg. 您可能希望将容器中的所有HTML重新显示为不同的值,例如。 as HTML markup, as text, as HTML-encoded text. 作为HTML标记,文本,HTML编码文本。 With that I mean HTML entities (eg. &gt; for > (greater than sign)). 我的意思是HTML实体(例如&gt;代表> (大于符号))。 Here are the methods for displaying different types of output each time: Here's a variable for the subsequent code: 以下是每次显示不同类型输出的方法:这是后续代码的变量:

var target = document.getElementById('text-output'); // for later

1. HTML in a container element 1.容器元素中的HTML

  • Output: Rendered HTML 输出:呈现的HTML
  • Javascript: Javascript:
target.innerHTML = html;

2. Text in a container element 2.容器元素中的文本

  • Output: Text, HTML entities encoded 输出:文本,HTML实体编码
  • Javascript: Javascript:
// will automatically encode HTML entities
var text = document.createTextNode(html); 
target.innerHTML = text;

3. HTML in a textarea element 3. textarea元素中的HTML

  • Output: Text, HTML entities non-encoded 输出:文本,未编码的HTML实体
  • Javascript: Javascript:
yourTextArea.value = html;

4. Text in a textarea element 4. textarea元素中的textarea

  • Output: Text, HTML entities encoded 输出:文本,HTML实体编码
  • Javascript: Javascript:
 // The virtual container automatically encodes entities when its .innerHTML
 // method is called after appending a textnode.
 var virtualContainer = document.createElement('div');
 var text = document.createTextNode(html); 
 virtualContainer.appendChild(text);
 yourTextArea.value = virtualContainer.innerHTML;

Demo: http://jsbin.com/mozibezi/1/edit 演示: http //jsbin.com/mozibezi/1/edit

PS: It is impossible to display the output from #4 in a non-form input. PS:不可能以格式输入显示#4的输出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM