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

3
  • Possible duplicate of How do I change the ID of a HTML element with JavaScript? Commented Apr 6, 2016 at 21:50
  • You cannot set the id to 'two' because another element already has that id. Commented Apr 6, 2016 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 Commented Apr 6, 2016 at 22:02

1 Answer 1

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/

Sign up to request clarification or add additional context in comments.

5 Comments

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?
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: '<script src="scripts/you_site.js"></script>'
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.
@PavelMorshenyuk what does nowrap do in jsfiddle? What would you use the different options for?
@paul-fitzgerald You can find this information here: doc.jsfiddle.net/basic/… First two options will not add the functions you declare into global scope. Such functions cannot be called from inline html.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.