Xasz
Xasz

Reputation: 101

How to get div text also with it's input's values

I was wondering how to obtain the text inside a given div, with also the input's values as text.

<div id="example">This is a <input type="text" value="right"/> test.</div>

If I just try to get text like this with jQuery :

$("#example").text();

The result would be This is a test. and I'd want : This is a right test. The number of input would be unknow. As well as the order of the elements...

EDIT : I finally resolved my own problem :

var finalText="";
   $("#example").contents().filter(function() {
        if(this.nodeType==3){ finalText =finalText+ this.nodeValue;}
        else if(this.nodeName=="INPUT"){ finalText=finalText+this.value;}
           return finalText
    })  

The living example

But @Jonathan Lonowski answer is more clear and simpler than mine !

Upvotes: 2

Views: 153

Answers (5)

Jonathan Lonowski
Jonathan Lonowski

Reputation: 123453

You might try cloning so you can replaceWith the inputs with their values. Then grab the text as you were:

var clone = $('#example').clone();

clone.find(':input').replaceWith(function () {
    return $(this).val();
});

alert(clone.text());

Upvotes: 2

Siva Charan
Siva Charan

Reputation: 18064

Using innerText

document.getElementbyId('example').innerText;

To get HTML tags:-

document.getElementbyId('example').innerHTML;

Refer this URL element.innerHTML

Upvotes: 0

gen_Eric
gen_Eric

Reputation: 227220

You can loop though all children of the <div> and replace then with their values. Something like this:

$.fn.allText = function(){
    var $this = this.clone();
    $this.children().each(function(){
        $(this, $this).replaceWith(this.value);
    });
    return $this.text();
};

alert($('#example').allText());

Demo: http://jsfiddle.net/4mGmH/

Upvotes: 1

Skylar Anderson
Skylar Anderson

Reputation: 5703

Here is a quick plugin that will do this for you:

$(document).ready(function() {

   $.fn.extend({
        getContentText: function() {
          var t = '';
          this.contents().each(function(i,c) {
              var method = $(c).is("input") ? "val" : "text";
              t += $(c)[method]();
          });
          return t;
        }
    });

    alert($("#example").getContentText());

});

Try it out here: http://jsfiddle.net/wQpHM/

Upvotes: 3

user973254
user973254

Reputation:

get html and strip html tags

$('#example')[0].innerHTML.replace(/(<([^>]+)>)/ig, '').replace(/(\s+)/g, ' ')

Upvotes: 0

Related Questions