Kenneth Deloso
Kenneth Deloso

Reputation: 1

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.

How can i get the text including it's HTML element?

Based on my example, I should get this:

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

Upvotes: 0

Views: 62

Answers (3)

webketje
webketje

Reputation: 10976

Since everyone is requiring OP to use jQuery, here's the native JS equivalent. You can select the html content of an element like so :

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

You might want to redisplay all the HTML from the container as different values, eg. as HTML markup, as text, as HTML-encoded text. With that I mean HTML entities (eg. &gt; for > (greater than sign)). 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

  • Output: Rendered HTML
  • Javascript:
target.innerHTML = html;

2. Text in a container element

  • Output: Text, HTML entities encoded
  • Javascript:
// will automatically encode HTML entities
var text = document.createTextNode(html); 
target.innerHTML = text;

3. HTML in a textarea element

  • Output: Text, HTML entities non-encoded
  • Javascript:
yourTextArea.value = html;

4. Text in a textarea element

  • Output: Text, HTML entities encoded
  • 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

PS: It is impossible to display the output from #4 in a non-form input.

Upvotes: 1

Funereal
Funereal

Reputation: 673

You should take the values adding a class or id.

HTML:

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

JS:

$('.test').html()

Live Example

Upvotes: 1

Suresh Ponnukalai
Suresh Ponnukalai

Reputation: 13988

Use jquery html selector to get the value with HTML selector.

HTML:

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

JS:

 $('#test').html()

Upvotes: 2

Related Questions