Home > Net >  select html element by its full html tag - JS
select html element by its full html tag - JS

Time:03-03

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)

CodePudding user response:

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;
   }
}

CodePudding user response:

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
  • Related