Reputation: 658
i have a div that contains some html and text (html is added dynamically)the structure would be like
<div id="contentContainer">
<span>ProductA</span> ; <span>ProductB</span>; prod
</div>
i want to remove the last incomplete text (prod) from the inner html of the div contentContainer on submit button click
for this i was using regex returnText.replace(/\w+$/, ''); and it works fine as i can not trim the text to last index of ';'
but not the issue is when user puts some special charaters in the incomplete text as pr\od the regex fails
so is there any solution to trim the last appended text the inner html of the div
or can i trim the text to the last html tag and place ; after that
please suggest any solution
Upvotes: 0
Views: 740
Reputation: 171679
Solution looks at the last DOM node in DIV, if it is a text node it changes text to semi-colon
var lastNode = $('#contentContainer').contents().last()[0]
if (lastNode.nodeType == 3) {
lastNode.textContent=';'
}
demo: http://jsfiddle.net/EhcLh/
Upvotes: 1
Reputation: 5421
if you are using jquery you can pull out all span elements and replace innerHTML with them.
$("#contentContainer").html( $("#contentContainer span") );
That should clean rest things. Maybe not the best but i think its better then regexp on content.
Upvotes: 2