Sai
Sai

Reputation: 7209

CSS/JavaScript: get user-visible text of an element

Suppose I have the following HTML:

<div id="test">
  <span style="display:inline;">foo</span>
  <span style="display:none;">bar</span>
  <span style="display:inline;">baz</span>
</div>

.. is there some way in JavaScript for me to get the output "foo baz" (not "foo bar baz")?

$('test').textContent returns the latter, and innerHTML does the equivalent.

I don't care at all if the method used is hackish or roundabout, and can deal with it if it's browser-specific or requires Flash.

However, it must not require anything other than JS or Flash, it must not require any user interaction, and it must not return 'bar'.

Ideas?

Upvotes: 5

Views: 3785

Answers (1)

Nick Craver
Nick Craver

Reputation: 630409

You can do this, but note it won't have a space like your example, because there is no space in the markup:

$("#test :visible").text()

Here's an alternative, like your example spaced out for each span:

var s = new Array();
$("#test :visible").each(function() {
   s.push($(this).text());
});
alert(s.join(' '));

Upvotes: 4

Related Questions