Question

I know jsFiddle displays it's results in an iFrame. I am taking a JS class right now and according to my instructor, "getElementById" is the most used function in all of JS.

So why doesn't "getElementById" work in jsFiddle:

document.getElementById("myH1")

However...

document.getElementsByTagName("H1")

Does work!

See my fiddle for the example:

http://jsfiddle.net/uM9t4/

Était-ce utile?

La solution 2

it does, its just your thinking of how replace works is wrong, it does not do an inline change it returns the changed string, if it didnt work you would be getting an

Cannot call method 'getAttribute' of null


document.getElementById("myH1").getAttribute("class").replace("bye","NO");

should be

var change = document.getElementById("myH1").getAttribute("class").replace("bye","NO");
document.getElementById("myH1").setAttribute("class",change);

JSFiddle

Autres conseils

document.getElementById("myH1") does work.

I think what you are trying to do is change the attribute of class from having "bye" to having "NO", which doesn't work. You are getting the class and changing it properly, but it is just a string. You have to then reassign it back to the class attribute.

document.getElementById("myH1").setAttribute('class', document.getElementById("myH1").getAttribute("class").replace("bye","NO"));

Or, stashing the element in a variable:

var myH1 = document.getElementById("myH1");
myH1.setAttribute('class', myH1.getAttribute('class').replace('bye', 'NO'));
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top