Home > front end >  querySelector to find a DOM element which has particular text anywhere inside its tree
querySelector to find a DOM element which has particular text anywhere inside its tree

Time:04-04

<div>
    <card >
        <header >Title 1</header>
    </card>
    <div>Stuff</div>
    <card > <-- This one
        <header >Title 2</header>
    </card>
    <div>More stuff?</div>
    <card >
        <header >Title 3</header>
    </card>
</div>

I would like to pull out the DOM element as noted in the example using 2 conditions. The dom element I am interested in has a class card-class and somewhere inside this DOM element there is an element with class header-class which has a title inside.

I need to get a particular card BY the title text. So in this example I want the card element with 'Title 2'. Is there any way to ahcieve this with just a selector rather than javascript?

CodePudding user response:

Not sure it´s possible with a one-liner, but here is an alternative:

First you get all the "header-class", that are descendant of "card-class". Then you loop through them looking for requested title. And finally you access the parent component, which is the card you are looking for.

const cards = document.querySelectorAll(".card-class .header-class");

for (let card of cards) {
    if (card.innerHTML === "Title 2") {
        let cardYouAreLookingFor = card.parentElement;
        console.log(cardYouAreLookingFor);
    }
}

Hope this helps. Cheers!

CodePudding user response:

The only possible way I can see this working with one line is if you add a data attribute to the element, and then target that.

const title2 = document.querySelector('.header-class[data-title="Title 2"]');

console.log(title2.textContent);
<div>
  <card >
    <header  data-title="Title 1">Title 1</header>
  </card>
  <div>Stuff</div>
  <card >
    <header  data-title="Title 2">Title 2</header>
  </card>
  <div>More stuff?</div>
  <card >
    <header  data-title="Title 3">Title 3</header>
  </card>
</div>

  • Related