[英]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()
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.
>
for >
(greater than sign)). 我的意思是HTML实体(例如
>
代表>
(大于符号))。 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
target.innerHTML = html;
// will automatically encode HTML entities
var text = document.createTextNode(html);
target.innerHTML = text;
textarea
element textarea
元素中的HTML yourTextArea.value = html;
textarea
element textarea
元素中的textarea
// 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.