Searching through the Document Object Model (DOM) can allow one to identify and/or modify root (ie: parent) and subroot elements (ie: children, sibling). The following are ways to search through the DOM:
- querySelector,
- querySelectorAll
- tilda sibling notation in CSS.
Way 0: use querySelector
<!DOCTYPE>
<html>
<head></head>
<body>
<div class="javascript_css"></div>
<script>
function functionName0() {
var divElement = document.createElement("div");
divElement.setAttribute("id", "div0");
divElement.setAttribute("class", "div_simple");
divElement.style.position = "absolute";
divElement.style.top = "0px";
divElement.style.left = "85px";
divElement.style.width = "200px";
divElement.style.height = "200px";
divElement.style.display = "flex";
divElement.style.border = "2px solid gray";
divElement.style.borderRadius = "5px";
divElement.style.flexDirection = "column";
divElement.style.gap = "2px";
document.getElementsByClassName("javascript_css")[0].appendChild(divElement);
for (var i=0; i<2; i++) {
var pElement = document.createElement("p");
pElement.setAttribute("id", "p"+i);
pElement.setAttribute("class", "p_simple");
pElement.style.backgroundColor = "floralwhite";
pElement.style.width = "100px";
pElement.style.height = "30px";
pElement.style.border = "2px solid gray";
pElement.innerText = "Text";
divElement.style.borderRadius = "2px";
document.getElementById("div0").appendChild(pElement);
}
// document.querySelector("#div0:hover")
const matches = document.querySelectorAll(".p_simple");
document.getElementById("div0").innerHTML += "matches: "+matches+"<br>";
document.getElementById("div0").innerHTML += "matches.length: "+matches.length+"<br>";
for (var i=0; i<matches.length; i++) {
document.getElementById("div0").innerHTML += "matches: "+matches[i]+"<br>";
}
}
</script>
<script>
sidebar();
function sidebar() {
document.getElementsByClassName("javascript_css")[0].style.position = "absolute";
document.getElementsByClassName("javascript_css")[0].style.width = "75px";
document.getElementsByClassName("javascript_css")[0].style.height = "200px";
document.getElementsByClassName("javascript_css")[0].style.border = "1px solid gray";
document.getElementsByClassName("javascript_css")[0].style.borderRadius = "2px";
document.getElementsByClassName("javascript_css")[0].style.fontSize = "12px";
document.getElementsByClassName("javascript_css")[0].innerText = "Ways to search the Document Object Model (DOM)";
functionName0();
}
</script>
</body>
</html>
Good Luck with your workflows and Happy Practicing! 👋
💻 GitHub | 🌷 Practicing Datscy @ Dev.to | 🌳 Practicing Datscy @ Medium
Top comments (0)