Home > database >  How to find specefic HTML element by keyword?
How to find specefic HTML element by keyword?

Time:07-01

I'm having problems on how to find a specifique HTML element when having a keyword:

<div >
    <div  >
        <div >
        
            <div  >
                
                <div >
                    COMPUTIME
                </div>

my keyword is COMPUTIME aand I whant to detect className of this div

<div >

CodePudding user response:

You can try this with JavaScript:

for (const a of document.querySelectorAll(".ct-product--tilte")) {
  if (a.textContent.includes("COMPUTIME")) {
  console.log(a.textContent)
  }
}

CodePudding user response:

As I understand, you want to get element class by searching on the TEXT in your div, then you can try something like this:

var allElement = document.querySelectorAll('*');
var myElement = null;

var valueToSearch = "COMPUTIME"; 

allElement.forEach(el => {
  if(el.innerHTML.trim() === valueToSearch) {
    myElement = el;
  }
})

console.log(myElement) // My element HTML
console.log(myElement.className) // My Class 
console.log(myElement.id) // My id

var parentSearching = true;

while(parentSearching) {
  myElement = myElement.parentElement;
  if (myElement.className.includes('col')) {
    parentSearching = true;
    break;
  }
}

console.log(myElement.className); // col-sm-6 col-md-6 col-lg-4
<div >
  <div  >
    <div >
      <div  >
        <div >
          COMPUTIME
        </div>        
      </div>
    </div>
  </div>
</div>

  • Related