I want jQuery to allow me to select only the most recent element when I select an element in the *:contains('AAA') selector.

Asked 1 years ago, Updated 1 years ago, 446 views

<table>
<tr><td>AAA</td></tr>
<tr><td>BBB</td></tr>
</table>

If there is HTML,

In jQuery

$("*:contains('AAA')").addClass('hoge');

In that case, class is given to all elements that contain the text of AAA, including ancestral elements.

<table class="hoge">
<tr class="hoge"><td class="hoge">AAA</td></tr>
<tr><td>BBB</td></tr>
</table>

(behavior as per specification)

Probably from a raw Javascript perspective

constructions= document.querySelectorAll('*');
const filterElements=Array.from(elements).filter(element)=>element.textContent.indexOf('AAA')!==-1);
for (el of filterElements) {
    el.classList.add('hoge');
}

I think it's similar to
Is it possible to select only the most recent element?

I want it to look like this:

<table>
<tr><td class="hoge">AAA</td></tr>
<tr><td>BBB</td></tr>
</table>

One solution is

$("*:contains('AAA'):not(:has(>*))") .addClass('hoge');

I could have done something close, but
In this case,

<table>
<tr><td><br>AAA</td></tr>
<tr><td>BBB</td></tr>
</table>

It doesn't work well with other elements, such as .

javascript query

2022-12-18 07:10

1 Answers

:contains() is described in

The matching text can appear directly with the selected element, in any of those element's descendants, or a combination thereof.

As mentioned above, I have no choice but to accept the fact that all descendants are searched for text nodes.As discussed in the questionnaire, we have no choice but to make some other conditions.

For example, if you want to limit yourself to <TD> tags,

$("td:contains('AAA')").addClass('hoge');

If so, <TABLE> and <TR> will no longer match.

Or, for example, investigate and deny child nodes. (I didn't try the code.)

$(":contains('AAA'):not(:has(>:contains('AAA')))") .addClass('hoge');

However,

<div>
  AAA
  <p>AAA</p>
</div>

In the case of , there are side effects that can be denied up to the outside <DIV>.


2022-12-18 11:58

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.