Home > Blockchain >  Find an element that contain certain character using javascript
Find an element that contain certain character using javascript

Time:01-28

i want to detect the parent of element that has "_" character in it

that could be achieved using jquery and css3 selcetor ":contain" like the following

$('.class a:contains("_")').parent()

but im trying to avoid using jquery too much , so is there any way to do this using native js

CodePudding user response:

There is no CSS to check if it contains text. Only way you can do text matching is if that text happened to be in an attribute on the element. So you are going to have to select all the parent elements and loop over them looping at the text/children's text.

To do that you can select all the elements and use filter to check the text. If you only care there is an underscore you can just text the text content of the element.

const elemsWithUnderscore = [...document.querySelectorAll('.yourClass')].filter(el => el.textContent.includes('_'));

console.log(elemsWithUnderscore);
<div ><a>a</a></div>
<div ><a>b_</a></div>
<div ><a>c</a></div>
<div ><a>d_</a></div>
<div ><a>e</a></div>

If it only can be in the anchor tag and there is one you can selector the anchor tag.

const elemsWithUnderscore = [...document.querySelectorAll('.yourClass')].filter(el => [...el.querySelectorAll('a')].some(a => a.textContent.includes('_')));

console.log(elemsWithUnderscore);
<div >_<a>a</a></div>
<div ><a>b</a><a>b_</a></div>
<div ><a>c</a></div>
<div ><a>d_</a></div>
<div ><a>e</a></div>

If there is more than one anchor as children then you need to use some to see if one of them has an underscore.

const elemsWithUnderscore = [...document.querySelectorAll('.yourClass')].filter(el => el.querySelector('a')?.textContent.includes('_'));

console.log(elemsWithUnderscore);
<div >_<a>a</a></div>
<div ><a>b_</a></div>
<div ><a>c</a></div>
<div ><a>d_</a></div>
<div ><a>e</a></div>

CodePudding user response:

You can use document.querySelectorAll and check the textContent of the children.

[...document.querySelectorAll('.class')].filter(el => 
  [...el.querySelectorAll('a')].some(a => a.textContent.includes('_')))
  .forEach(el => console.log(el.outerHTML));
<div ><a>_</a></div>
<div >
  <div><a>abc_def</a><span>123</span></div>
</div>
<div><a>nothing to see</a></div>

  • Related