Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Find an element that contain certain character using javascript

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()

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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 class="yourClass"><a>a</a></div>
<div class="yourClass"><a>b_</a></div>
<div class="yourClass"><a>c</a></div>
<div class="yourClass"><a>d_</a></div>
<div class="yourClass"><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 class="yourClass">_<a>a</a></div>
<div class="yourClass"><a>b</a><a>b_</a></div>
<div class="yourClass"><a>c</a></div>
<div class="yourClass"><a>d_</a></div>
<div class="yourClass"><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 class="yourClass">_<a>a</a></div>
<div class="yourClass"><a>b_</a></div>
<div class="yourClass"><a>c</a></div>
<div class="yourClass"><a>d_</a></div>
<div class="yourClass"><a>e</a></div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading