Bri
Bri

Reputation: 739

Remove element from html string in JQuery

So, I am pretty stumped as to how to exclude a sub children from getting selected in JQuery...

Here is my HTML structure in my string:

<table>
   <tr>
       <td>some data I don't want.</td>
       <td>
       <table><tr><td>more data I don't want</td></tr></table>
       Text I want to extract here.
       </td>
   </tr>
</table>

Note: I didn't choose this. I am trying to parse the text "Text I want to extract here" out of this structure that comes from some arbitrary xml feed.

Here is my test JQuery: (d is the HTML string)

$('tr > td:eq(1) > table', d).remove();
var c = $('tr > td:eq(1)', d).text();

The first line does not remove the table. I test the selector and it does manage to select the element. Am I using the wrong method to remove the element?

I had also tried using not() and replaceWith() with no luck.

$('tr > td:eq(1)', d).not('tr > td:eq(1) > table').text();

and

$('tr > td:eq(1) > table', d).replaceWith("");

I am open to other selection methods that will retrieve only the text within that specific td.

Upvotes: 4

Views: 8151

Answers (2)

RightSaidFred
RightSaidFred

Reputation: 11327

You state that "d is the HTML string".

This means that when you do this:

$('tr > td:eq(1) > table', d).remove();
var c = $('tr > td:eq(1)', d).text();

...you're creating elements from the same unmodified string twice.


You need to create elements out of it once, then cache those elements.

var $d = $(d);  // create the elements out of the string, and cache the set

$d.find('tr > td:eq(1) > table').remove();  // remove table from the cached set
var c = $d.find('tr > td:eq(1)').text(); // target the <td> and get its text

JSFIDDLE DEMO


Or, because of jQuery's .end() method, you could do it all in one shot like this:

var c = $(d).find('tr > td:eq(1)')
            .children('table')
            .remove()
            .end()
            .text();

JSFIDDLE DEMO

Upvotes: 3

Abe Miessler
Abe Miessler

Reputation: 85056

What is d? When I created an example of your js/HTML it seemed to run fine. You can see it here:

http://jsfiddle.net/v7Qm2/

Is it possible that you are limiting the scope to d when you should not be?

NOTE:

Just to clarify, my answer is that your code looks fine and appears to do what you want. I think the issue is that you are limiting the scope of your selector when you should not.

Upvotes: 2

Related Questions