javascript - jQuery need to change only text content in an element -
i have 2 li
elements having icon,text in each element. want change first li icon , text on button click. replacing whole anchor tag content if use .text()
$(document).ready(function(){ $("#changeicon").click(function(){ $("#listitems li:eq(0) span").removeclass("ic1").addclass("ic3"); //$("#listitems li:eq(0) a").text("icon3");//uncomment line , check }); });
span { display:block; width:32px; height:32px; } .ic1 { background:url("https://cdn4.iconfinder.com/data/icons/wirecons-free-vector-icons/32/menu-alt-32.png") no-repeat; } .ic2 { background:url("https://cdn0.iconfinder.com/data/icons/navigation-set-arrows-part-one/32/grid-32.png") no-repeat; } .ic3 { background:url("https://cdn2.iconfinder.com/data/icons/4web-3/139/menu-32.png") no-repeat; } .ic4 { background:url("https://cdn3.iconfinder.com/data/icons/eightyshades/512/45_menu-32.png") no-repeat; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <ul id="listitems"> <li> <a href=""> <span class="ic1"></span> icon1 <span class="ic1"></span> </a> </li> <li> <a href=""> <span class="ic2"></span> icon2 <span class="ic2"></span> </a> </li> </ul> <input type="button" id="changeicon" value="change 1 3">
is there way can change text only?
please don't provide me $("#listitems li:eq(0) a").html('<span class="ic3"></span>icon3<span class="ic3"></span>')
? know.
if can't put text in it's own span element, try this:
$(document).ready(function(){ $("#changeicon").click(function(){ $("#listitems li:eq(0) span").removeclass("ic1").addclass("ic3"); $("#listitems li:eq(0) a").contents().filter(function() { return this.nodetype === 3; //node.text_node })[1].textcontent = "icon3"; //$("#listitems li:eq(0) a").text("icon3");//uncomment line , check }); });
span { display:block; width:32px; height:32px; } .ic1 { background:url("https://cdn4.iconfinder.com/data/icons/wirecons-free-vector-icons/32/menu-alt-32.png") no-repeat; } .ic2 { background:url("https://cdn0.iconfinder.com/data/icons/navigation-set-arrows-part-one/32/grid-32.png") no-repeat; } .ic3 { background:url("https://cdn2.iconfinder.com/data/icons/4web-3/139/menu-32.png") no-repeat; } .ic4 { background:url("https://cdn3.iconfinder.com/data/icons/eightyshades/512/45_menu-32.png") no-repeat; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <ul id="listitems"> <li> <a href=""> <span class="ic1"></span> icon1 <span class="ic1"></span> </a> </li> <li> <a href=""> <span class="ic2"></span> icon2 <span class="ic2"></span> </a> </li> </ul> <input type="button" id="changeicon" value="change 1 3">
Comments
Post a Comment