开发者

JQuery adding class

I am trying to add a class on the following div using JQuery and I don't know what I am doing incorrectly.

<div class="flash alert">You need to sign in or sign up before continuing.</div>

I want to remove the alert class and add the classes alert-message, and error. I have been using the following code which hasn't been working:

$('div flash alert').removeclass('.alert').addClass('.alertMessage .error');

I can't edit the css directly, if I could go that path I would.

Here is a jsfiddle link of exactly what I have written. It works in the jsfiddle but not on my page: http://jsfiddle.net/uR3gz/2/ Here is what it looks lik开发者_如何转开发e on my page: http://imgur.com/a/eZCyj#2

Notes: I am using rails with devise and I am trying to get rid of the default alert message.

Note I got the whole thing to work by wrapping it in an anonymous function like so:

$(function() {
  $('div.flash.alert').removeClass('alert').addClass('alert-message error');
});


There are lots of issues with this.

$('div flash alert')

That selects alert elements inside flash elements inside div elements. I think you want div.flash.alert.

.removeclass('.alert')

You need removeClass (capitals matter) and 'alert'. You don't need the dot since it's not part of the class name.

.addClass('.alertMessage .error');

Again, you don't need the dots.


So the final solution may look like this:

$('div.flash.alert').removeClass('alert').addClass('alertMessage error');

So, on top of all your syntax problems, you were running the code before the document was parsed, so the element you were trying to select didn't exist yet. The solution to this is to use an event listener on the document's ready event:

$(document).ready(function(){...});
$(function(){...}); // shortcut for the above code


try

$('div .flash .alert').removeclass('alert').addClass('alertMessage error');


$('div.flash.alert').removeClass('alert').addClass('alertMessage error');

Note this changes all divs with the class="flash alert", if you want to change a specific div it might be better to give it an id, then you can select it with $('#myId')

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜