how to find a html element and then remove it? [duplicate]
Possible Duplicate:
Facing weird problem while adding and removing class.
Suppose I have the following html--
<div class="div_portlet ui-widget ui-widget-content ui-corner-all defaultcontentbg portlet-width default_border default_border_color portlet_space">
<div class="div_header headertitle align_center defaultheadercolor portlet-header-left-padding default_bottom_border default_border_color">
<span class="ui-icon ui-icon-minusthick"></span>
Order Header Level Information</div>
<div id="ordrHdrLvnInfn" class="div_content portlet-width">
What I am trying to do is, check whether span with class ui-icon ui-icon-minusthick
exists or not, if it exists first remove it and then add it. I tried in following way, but it's not working
javascript function::
jQuery.fn.initPortlet = function( parent_component ,header , component ){
this.find(header).find('span.ui开发者_JAVA百科-icon').remove();
this.addClass("ui-widget ui-widget-content ui-corner-all")
.find(header)
.addClass("headertitle")
.addClass("align_center")
.addClass("defaultheadercolor")
.end()
.prepend('<span class="ui-icon ui-icon-minusthick"></span>')
.find(component);
}
and I am calling this function in this way..
$('.div_portlet').initPortlet('.div_portlet','.div_header','.div_content')
It should first remove the span then add it, but if I am calling this function multiple times then it just keep on adding that span.
How can I do this or is there any better way to do this. Thanks!!!!You are adding your span outside the div_header. Your .end() means you are no longer working with your header filter so the span is getting added to the beginning of your ui_widget...
http://jsfiddle.net/Qjrcg/ is a fiddle of your code. If you look I have a commented out .end() just after the prepend. If you uncomment this and comment out the earlier one then the span (which I put test text in to make it easier to see) only gets created once.
Hopefully this should sort you out.
I think the problem is in your first find
this.find(header).find('span.ui-icon').remove();
you are trying to find the icon inside the header but you are prepending the next icon to the portlet (this)
.prepend('<span class="ui-icon ui-icon-minusthick"></span>')
so try this
this.find('span.ui-icon').remove();
Check out the update which I did to Chris's fiddle: http://jsfiddle.net/Qjrcg/5/
HTH
精彩评论