On a SharePoint landing page I have several CQWP that place an ID multiple times in the DOM. I want to access the second and only the second ID called hiddenArea.

I can't change the control in any fashion and I need to use javascript code below modified with the fix as a solution.

<script type="text/javascript">
var a = document.createElement('a');
var linkText = document.createTextNode("My Assignments");
a.title = "My Assignments";
a.href = "/ourcompany/departments/insretsol/grpptr/Lists/TDM%20Select%20an%20Assignment/Applicant%20View.aspx";
a.className += "noContentLink"
<style type="text/css">
    display:inline-block !important;
    text-align:center !important;
    /*text-align:right !important;*/

Having multiple elements with the same ID is invalid HTML. getElementById will only return the first one (or one at least).

You may be able to use:

  var elems = document.querySelectorAll("#hiddenArea");
  // elems[1] has the 2nd one
| improve this answer | |
  • I totally get that it is invalid HTML but we have no other options. Would you replace this document.getElementById('hiddenArea').appendChild(a); with this var elems = document.querySelectorAll("[id='hiddenArea']"); ? – Kenneth Kerr Jan 18 '18 at 14:58
  • Note: I changed how I referenced the ID above - I think this will work also. – mannaggia Jan 18 '18 at 16:37
  • I think you can get away with just replacing the getElementById with: document.querySelectorAll("#hiddenArea")[1].appendChild(a); Of course this has no error checking, so it assumes there are always two elements with hiddenArea as the ID... – mannaggia Jan 18 '18 at 16:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.