Get Element By Classname Script Not Working

限于喜欢 提交于 2019-12-05 22:35:44

getElementsByClassName returns a collection. You might need to loop through the results, like this:

var elements = document.getElementsByClassName('editp');
for(var i=0; i<elements.length; i++) { 
  elements[i].style.display='none';
}
  • elements is a live NodeList of found elements in the order they appear in the tree.
  • names is a string representing the list of class names to match; class names are separated by whitespace
  • getElementsByClassName can be called on any element, not only on the document. The element on which it is called will be used as the root of the search.

Should go through this.

There may be unterminated string literals in the markup you create. It also appears there may be other issues as mentioned in other posts.

Change:

 "<a href=\"#\">Edit Mode: <span style=\"color:red;>OFF</span></a>";

to

"<a href=\"#\">Edit Mode: <span style=\"color:red;\">OFF</span></a>";

This situation is also present in the other markup you create.

Change:

"<a href=\"#\">Edit Mode: <span style=\"color:green;>on</span></a>";

to

"<a href=\"#\">Edit Mode: <span style=\"color:green;\">on</span></a>";

getElementsByClassName returns a NodeList (or an array if it's not built-in), but you're using it as though it were an HTMLElement by referring directly to a style property on it:

getElementsByClassName("editp").style.display ="none";
// here ------------------------^

You should be seeing an error in the JavaScript console, since you're trying to retrieve the property display from undefined (since getElementsByClassName("editp").style will be undefined).

If you want to act on the first matching element:

var elm = getElementsByClassName("editp")[0];
if (elm) {
    elm.style.display ="none";
}

...or if you want to act on all of them:

var index;
var list = getElementsByClassName("editp");
for (index = 0; index < list.length; ++index) {
    list[index].style.display ="none";
}

Update:

At some point, you edited the question and removed var toggle = "off" from the code (at global scope, just above the function) and made toggle an argument to editToggle. But you're not passing anything into editToggle according to your quoted markup, and even if you were, setting toggle to a new value within the function won't have any lasting effect if it's a function argument, as nothing refers to it after the function returns.

Ertug

You seem to have a missing semicolumn after var toggle="off".

Make sure that you call editToggle() somewhere in your code.

I advise you to use inspectors built into browsers or extensions. For example Firebug extension for Firefox or Chrome Inspector. Use the console to debug and see if there are errors in your javascript.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!