Possible Duplicate:
JQuery to check for duplicate ids in a DOM
Suppose i have a code:
<div id="one">
<div id="two"></div>
<div id="three"></div>
</div>
<div id="four">
<div id="two"></div>
</div>
<div id="one">
<p id="five">
<span id="three"></span>
</p>
</div>
(a large HTML code with different DOM items).
Objective:
Is it possible to build a jQuery or JavaScript code that will alert me about duplication of ids within the document with the position. Here the position means like following;
> duplicate id: 'div#two' > within `div#four`, `div#one`
> duplicate id: 'div#one' > parent of `p#five`
> duplicate id: 'span#three' > within `p#five` and such a pattern.
Note:
I found a problem similar to me, but not exact. As it is not duplicate of any question asked before. So don’t CLOSE IT.
NOTE: Read all caveats. The point of this code is to illustrate the nature of the problem, which is that a pure JS solution is inadvisable.
First of all, hopefully what this is illustrates is that sometimes things that are doable are not always advisable. There are a ton of awesome tools out there that will provide far better error checking, like W3C’s validator or add-ins/extensions that utilize it, like Validity for Chrome. Definitely use those.
But anyway, here’s a minimalist example. Note that none of the DOM has references to its own line number, so you have to get the entire
innerHTMLattribute from thedocumentElementas a string. You match parts of that string, then break it into a substring at the match position, then count the number of carriage returns. Obviously, this code could be extensively refactored, but I think the point is clear (also jsFiddle example for those who want it, although the lines will be fubar):EDIT
I’ve updated the regex to not match examples like
<div>id="a"</div>. Still, if the OP wants something pure JS, he’ll have to rely on this or a considerably more complex version with very minor benefits. The bottom line is that there are no associations between DOM nodes and line numbers. You will have to, on your own, figure out where the ID attributes are and then trace them back to their position. This is extremely error-prone. It might make some sense as programming practice but is extremely inadvisable in the real world. The best solution — which I’m reiterating for the fourth time here — is an extension or add-in that will just send your page on to a real validator like the W3C’s.The code below is designed to “just work,” because there is no good way to do what the OP is asking.