Andres SK
Andres SK

Reputation: 10974

jQuery .text() grabbing text that matches condition

Once the user triggers an action, h1.text() has to be the same as h2.text().

$('h1').text($('h2').text());

The problem is that h2 has some spans and hidden spans inside. E.g.:

<h2>Countries: <span class="ec">Ecuador</span> <span class="cl hidden">Chile</span></h2>

h1 needs to be:

Countries: Ecuador

Chile should be left out because it is inside a span with the hidden class. I know this can be achieved with conditions somehow. Any ideas?

Upvotes: 2

Views: 148

Answers (1)

Ben Lee
Ben Lee

Reputation: 53319

Clone the h2 element (so we don't mess up the original), then find and remove all the span.hidden elements, then get the text back (using end to go back up the jquery chain from the removed hidden spans back to the h2) and apply it to h1:

$('h1').text($('h2').clone().find('span.hidden').remove().end().text())

jsFiddle: http://jsfiddle.net/mhUEr/1/

Upvotes: 2

Related Questions