KJW
KJW

Reputation: 15251

jquery: replace inner child elements with it's text so that the outer element's text returns text only?

Consider an element containing text. <h1>Title text <span>inner text</span></h1> or <h1>Title text <span>inner <b>text</b></span></h1>

When it's rendered it looks as Title text inner text, but in reality, when I want to get the text content of h1 it returns the inner child elements as well.

How do I make sure that all cases like this are formatted to the following?

<h1>Title text inner text</h1>

Basically removing any decorative inner elements? I need to select an element by it's text value and unfortunately these inner child elements interfere. For example when I try to match an element by xpath like *[text()='Title text inner text'], it cannot find it because there are inner child elements. To the human reader, it seems natural as the text is seemingly confined in it's own but the underlying html structure says otherwise.

Upvotes: 0

Views: 176

Answers (3)

gaurav5430
gaurav5430

Reputation: 13902

you can use the innerText property. It returns all the text.

http://help.dottoro.com/ljhvexii.php

usage:

var elem = document.getElementById ("myDiv");
message += "\ninner text : " + elem.innerText;

alert (message);

see this fiddle here :

http://jsfiddle.net/wxnY4/

Upvotes: 0

BillyJMcDonald
BillyJMcDonald

Reputation: 71

I think you are looking for something like this: http://jsfiddle.net/VwTHF/173/

var temp='<h1>Title text <span>inner <b>text</b></span></h1>';

var $temp = $(temp).find('span, b ,h1').contents().unwrap().end().end();

Although Barmar's solution look very viable as well.

Upvotes: 1

Barmar
Barmar

Reputation: 781751

This will set all the h1 elements' text to just the text without extra HTML:

$('h1').text(function(i, orig) { return orig; } );

Upvotes: 0

Related Questions