skip to Main Content

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

2

Answers


  1. 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 class="class"><a>_</a></div>
    <div class="class">
      <div><a>abc_def</a><span>123</span></div>
    </div>
    <div><a>nothing to see</a></div>
    Login or Signup to reply.
  2. 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>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search