You can try something like this:
function searchelement(elementhtml){
[...document.querySelectorAll("*")].forEach((ele)=>{
if(ele.outerHTML == elementhtml){
ele.classList.add("mystyle");
}
});
}
You can try something like this:
function searchelement(elementhtml){
[...document.querySelectorAll("*")].forEach((ele)=>{
if(ele.outerHTML == elementhtml){
ele.classList.add("mystyle");
}
});
}
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>
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”); } }); }
Please suggest me something as from foreach I am getting only one element. May be we need to implement some kind of recursive function.
Thanks your code is really great just a small modification and its working fine.
@arn48 Just read this answer, you will get understand everything