0

I can't seem to get this to work at: https://jsfiddle.net/xc6htkn4/4/

<body>
  <p id="one">One</p>
  <p id="two">Two</p>
  <p id="three">Three</p>
  <p id="four">Four</p>
  <p>
    <button onclick="changeId()">Try it</button>
  </p>  
</body>

#one {
  color: red;
}

#two {
  color: blue;
}

function changeId() {
  var el = document.getElementById('one');
  el.id = 'two';
}

What is wrong with the code? It appears to be correct. I am simply trying to change the id on a click event.

Thanks!

Edit: My settings were not appropriately set in jsfiddle

PPJN
  • 332
  • 3
  • 13
  • Possible duplicate of [How do I change the ID of a HTML element with JavaScript?](http://stackoverflow.com/questions/1650299/how-do-i-change-the-id-of-a-html-element-with-javascript) – Josh C. Apr 06 '16 at 21:50
  • You cannot set the id to `'two'` because another element already has that id. – ConnorsFan Apr 06 '16 at 21:52
  • While it isn't best practice, it appears to function correctly. I've updated the code to not have dupe id's – PPJN Apr 06 '16 at 22:02

1 Answers1

1

You code is fine, you just need to change the way jsfiddle loads the js code. Click on "javascript" button and select "Load Type" to be "No wrap - in <body>"

Working example: https://jsfiddle.net/xc6htkn4/5/

Pavel Morshenyuk
  • 10,891
  • 4
  • 32
  • 38
  • Thanks! Just learning the language. How would this be if I am writing HTML in a real webpage and want to separate my HTML and JS in separate files? – PPJN Apr 06 '16 at 22:04
  • There should be no problems with it. just create a 'script' element within your 'body' or 'head' tag, and link it to your separate js file: '' – Pavel Morshenyuk Apr 06 '16 at 22:10
  • You shouldn't use ID's because ID's are supposed to be used for only one element per page. If you want multiple elements to have the same CSS, use class instead. – Hawkeye Apr 06 '16 at 22:10
  • @PavelMorshenyuk what does nowrap do in jsfiddle? What would you use the different options for? – Paul Fitzgerald Apr 06 '16 at 22:14
  • @paul-fitzgerald You can find this information here: http://doc.jsfiddle.net/basic/introduction.html?highlight=load%20type#frameworks-and-extensions First two options will not add the functions you declare into global scope. Such functions cannot be called from inline html. – Pavel Morshenyuk Apr 06 '16 at 22:26