-2

I want to find an element from the html with the outerHTML. I don't want to find the element with the id or class I will only have the html as a string.I want an algorithm that will take raw html as a string and find it accordingly.

Please note on the code I have added a new class on that html. But not just want to add new class just want find the element and this is my main objective.

<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<script>
function findelement() {
  var element = document.getElementById("nestedh3").outerHTML;
  searchelement(element)
}
function searchelement(elementhtml) {
  //serch the whole content on the this html to find that element
  element = 
  //
  element.classList.add("mystyle");
}
</script>
<style>
.mystyle {
  width: 100%;
  padding: 25px;
  background-color: coral;
  color: white;
  font-size: 25px;
  box-sizing: border-box;
}
</style>
</head>
<body>
    <div>
        <h1>This is a Heading</h1>
        <p>This is a paragraph.</p>
        <div>
            <h3>Nested h3</h3>
        </div>
        <div>
            <div>
                <p>This is a nested paragraph</p>
            </div>
            <div>
                <h2>Nested h2</h2>
                <div id='nestedh3'>
                    <h3 id='nh3'>Nested h3</h3>
                </div>
            </div>
            <button onclick="findelement()">find element</button>
            <div>
                <p>This is a nested paragraph</p>
            </div>
        </div>

    </div>
</body>
</html>
arn48
  • 310
  • 4
  • 12

1 Answers1

4

You can try something like this:

function searchelement(elementhtml){
 [...document.querySelectorAll("*")].forEach((ele)=>{
   if(ele.outerHTML == elementhtml){
     ele.classList.add("mystyle");
   }
 });
}
Ritesh Khandekar
  • 3,885
  • 3
  • 15
  • 30
  • Hi Ritesh, Thanks a lot to put your valuable time to solve my question. And I also think it should work properly but its not working properly maybe because of my wrong implementation. Here is my code function searchelement(elementhtml) { [document.querySelectorAll("*")].forEach((ele)=>{ if(ele.outerHTML == elementhtml){ ele.classList.add("mystyle"); } }); } – arn48 Jan 19 '20 at 09:50
  • Please suggest me something as from foreach I am getting only one element. May be we need to implement some kind of recursive function. – arn48 Jan 19 '20 at 09:52
  • Thanks your code is really great just a small modification and its working fine. – arn48 Jan 19 '20 at 10:06
  • @arn48 Just read this answer, you will get understand everything https://stackoverflow.com/a/33982079/10273906 – Ritesh Khandekar Jan 19 '20 at 10:51