问题
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.
回答1:
There are so many ways to get info about your elements.
Using the innerHTML as 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
http://jsfiddle.net/a4J9U/
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.
If you explain more specifically why you need to get that span from a variable I can re-elaborate the code.
if you have any questions just ask.
回答2:
Here is what you want.
Here is html:
<label>opal fruits</label>
Here is jQuery:
$("label:contains(opal fruits)")
回答3:
var mySpans = document.getElementsByTagName(span);
for(var i=0;i<mySpans.length;i++){
if(mySpans[i].innerHTML == 'Home1'){
var parent = mySpans[i].parentNode;
break;
}
}
this selects the parent of span having innerHTML Home1
回答4:
innerHTML method return String type. It don't associate with DOM tree.
You can use jQuery and it contains selector(fiddle):
$(":contains('Home1')").last()
回答5:
var divRef; //Reference to the container of your div / span elements
var spans = divRef.getElementsByTagName("span");
var spanContainer;
for(var i = 0; i < spans.length; i++){
if(spans[i].innerHtml == "Home 1"){
spanContainer = spans[i].parentNode;
break;
}
}
if(spanContainer){
alert("Element has been found!");
}
来源:https://stackoverflow.com/questions/21452976/finding-element-using-its-innerhtml