Remove item from html string in jQuery

So, I'm pretty dead end on how to exclude child children from selected in jQuery ...

Here is my HTML structure in my line:

<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 did not select this. I am trying to parse the text โ€œText I want to extract hereโ€ from this structure, which comes from some arbitrary XML feed.

Here is my test jQuery: (d is an HTML string)

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

The first row does not delete the table. I am testing a selector and it manages to select an element. Am I using the wrong method to remove an item?

I 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 only extract text inside this particular td.

+4
source share
2 answers

You indicate that " d is an 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 double-create elements from the same unmodified string.


You need to create elements from it once , then cache these 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, due to the jQuery .end() method, you can do it all in one shot:

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

JSFIDDLE DEMO

+3
source

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

http://jsfiddle.net/v7Qm2/

Is it possible that you are restricting region d when you shouldn't be?

Note:

Just to clarify, my answer is that your code looks good and seems to do what you want. I think the problem is that you limit the scope of your selector when you don't want to.

+2
source

Source: https://habr.com/ru/post/1384368/


All Articles