Skip to content
Advertisement

jQuery search matching string and remove parent div

I’ve an HTML below:

<div id="keywords">
    <div id="container0">
        <span id="term010"> this</span>
        <span id="term111"> is</span>
        <span id="term212"> a</span>
        <span id="term313"> phrase</span>
    </div>

    <div id="container1">
        <span id="term014"> exact</span>
        <span id="term115"> match</span>
        <span id="term216"> type</span>
    </div>

    <div id="container2">
        <span id="term017"> this</span>
        <span id="term118"> is</span>
        <span id="term219"> a</span>
        <span id="term320"> broad</span>
    </div>
</div>

and I would like to remove the parent DIV (container) and it’s content if a child span contains a word, “this” for example.
The code should search for the word “this” on all spans and delete the divs with the Id “container0” and “container2”. I already have the Regex but I’m totally lost after that. I know that I should use querySelector but I never used it before and tried to make it work, but I failed.

/<span id="term[0-9]{3,}"> this</span>/gm

Thank you,

Advertisement

Answer

You can accomplish what you are looking for with jquery by doing something like the following (since you mentioned querySelector, you should know that it can be done with plain javascript as well – see the second code example below).

JQuery:

const spans = $('span');
spans.each(function(index, elem) {
  if (elem.textContent.toLowerCase().indexOf('this') >= 0) {
    elem.parentNode.remove();
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="keywords">
  <div id="container0">
    <span id="term010"> this</span>
    <span id="term111"> is</span>
    <span id="term212"> a</span>
    <span id="term313"> phrase</span>
  </div>
  <div id="container1">
    <span id="term014"> exact</span>
    <span id="term115"> match</span>
    <span id="term216"> type</span>
  </div>
  <div id="container2">
    <span id="term017"> this</span>
    <span id="term118"> is</span>
    <span id="term219"> a</span>
    <span id="term320"> broad</span>
  </div>
</div>

Javascript only:

const spans = document.querySelectorAll('span');
for (const span of spans) {
  if (span.textContent.toLowerCase().indexOf('this') >= 0) {
    span.parentNode.remove();
  }
}
<div id="keywords">
  <div id="container0">
    <span id="term010"> this</span>
    <span id="term111"> is</span>
    <span id="term212"> a</span>
    <span id="term313"> phrase</span>
  </div>
  <div id="container1">
    <span id="term014"> exact</span>
    <span id="term115"> match</span>
    <span id="term216"> type</span>
  </div>
  <div id="container2">
    <span id="term017"> this</span>
    <span id="term118"> is</span>
    <span id="term219"> a</span>
    <span id="term320"> broad</span>
  </div>
</div>
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement