Skip to content
Advertisement

How do I get just the visible text with jQuery (or Javascript)?

I have website that converts Japanese Kanji into Romaji (roman letters):

and the output shows and hides with CSS what the user needs to see depending on their input criteria. For example:

<div id="output"><span class="roman">watashi</span> <span class="english">I</span></div>

The interface allows the user to flip between and output of watashi or I depending on what they want to see. The CSS hides one or the other using jQuery and a toggle button. (the hiding mechanism involves simple adding a class to the body and letting CSS do its thing).

The problem is that when users copy/paste the text into Word it copies everything. So I decided to use a system to copy paste the text using JavaScript and jQuery, but the problem repeats itself:

$('#output').text() outputs watashi I even if I is invisible on the page itself rather than watashi. Is there any way to get just the visible text?

Advertisement

Answer

Use the :visible selector of jQuery

In your case I think you want to do:

$('#output').children(":visible").text() 
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement