Getting element node based on Javascript element based on position
I am experimenting with a Javascript function which stuffs nodes int开发者_JS百科o a position. Something like appendChild(document.getElementById("foo"))
. However, I do not have full control over the surrounding code and it is likely that some elements will have identical IDs. Consider the following:
<div id="foo">
<span id = "bar">456</span>
<script type="text/javascript">document.write(document.getElementById("bar").innerText);</script>
</div>
<hr>
<div id="foo">
<span id = "bar">123</span>
<script type="text/javascript">document.write(document.getElementById("bar").innerText);</script>
</div>
In most browsers, the output will be:
456 456
123 456
rather than what I want, which is
456 456
123 123
This result is totally unsurprising to me; I do understand why this is happening. I was hoping I could do a javascript call more like
document.write(myscriptnode.parent.childnodes['bar'].innerText)
Assuming I do not have control over anything except the contents of the script tags, is there a way to accomplish this?
Here is an incredibly horrifying way to solve this problem: Rather than trying to get the current node, create a new node with an arbitrary ID, then delete it when done.
<div id="foo">
<span id = "bar">456</span>
<script type="text/javascript">
document.write('<span id = "bfrogtmp"></span>');
var y = document.getElementById("bfrogtmp");
document.write(y.parentNode.children['bar'].innerHTML);
y.parentNode.removeChild(y);
</script>
</div>
<hr>
<div id="foo">
<span id = "bar">123</span>
<script type="text/javascript">
document.write('<span id = "bfrogtmp"></span>');
var y = document.getElementById("bfrogtmp");
document.write(y.parentNode.children['bar'].innerHTML);
y.parentNode.removeChild(y);
</script>
</div>
How about using a JavaScript library like jQuery, which allows you to write CSS-selector-like-syntax insead of getElementById, and also has useful helper methods such as parent().
http://jquery.com/
精彩评论