'select html element by its full html tag - JS

I am looking for a way to be able to select an HTML element by its tag, like:

document.querySelector("<div id='myDiv'\>hello world</div\>")
//instead of: document.querySelector("#myDiv")

However, this code returns an error. The code should return the HTML element.

Does anybody know a way to achieve this? (vanilla JS preferred)



Solution 1:[1]

It seems a bit odd that you wouldn't want to select element via ID. But regardless one way of selecting the element in your example would be to look for its innerHTML.

e.g

var div = document.getElementsByTagName('div');

for (var i=0;i<div.length;i++){
   console.log(div[i].innerHTML)
   if(div [i].innerHTML == 'hello world'){
       var element = div[i].parentElement
       console.log(element)
       break;
   }
}

Solution 2:[2]

You could use outerHTML to search for it, however this only works if the element has a parent element.

var els = Array.from(document.querySelector('body *')); //this selects all elements in the body
var el;
for(var i = 0; i < els.length; i++) {
  if(els.outerHTML === "<div id='myDiv'\>hello world</div\>") {
    el = els[i];
  }
}
//Use the el variable for your element

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Christian Smith
Solution 2 Shib