Finding element using its innerHTML

dom, html, javascript

Solution

There are so many ways to get info about your elements.

Using the innerHTML as an identifier is not a good solution.

You probably need some sort of event to that makes you search for that "Menu1"

So here is a click handler that works also on other events that give you information about what you have clicked.

function handler(e){
 var txt='You clicked on a '+e.target.nodeName+'\n';
    txt+='The innerHTML is '+e.target.innerHTML+'\n';
    txt+='The text is '+e.target.textContent+'\n';
    txt+='The parentNode is '+e.target.parentNode.nodeName+'\n';
 alert(txt)
}
document.addEventListener('click',handler,false)

DEMO

function handler(e) {
  var txt = 'You clicked on a ' + e.target.nodeName + '\n';
  txt += 'The innerHTML is ' + e.target.innerHTML + '\n';
  txt += 'The text is ' + e.target.textContent + '\n';
  txt += 'The parentNode is ' + e.target.parentNode.nodeName + '\n';
  alert(txt)
}

document.addEventListener('click', handler, false)
<div>
  <div><span>Menu1</span></div><span>Menu2</span><span>Menu3</span>
</div>

If you want that your script searches for that "Menu1" you should consider adding that "Menu1" as an attribute on the span or parentNode.

<div id="Menu1">
 <span>Home1</span>
</div>

and then call

document.getElementById('Menu1');

Which is very fast.

Problem

Please have a look to this DOM Tree... ``` <div> <div> <span> Home1 </span> </div> <span> Home2 </span> <span> Home3 </span> </div> ``` Now suppose I have a scenario where somehow I got the innerHTML of first span Home1. Is it possible to get the element span and its parent div by using only this (Home1) information.

Original source

Related problems