I have an ajax call returning various database fields one-by-one in a for loop. I’m able to test if the field is HTML by using:
for(i = 0; i < copyFromSchedule.length; i++) {
temporaryString = $(this).attr("ows_"+copyFromSchedule[i]);
if ($(temporaryString).html() == null)
// Is not HTML...
else
// Is HTML, remove any anchors found in this string (<a name="XXX"></a>)
$(temporaryString).find("a[name]").remove();
}
In the else statement (when the string is HTML), I’m trying to (unsuccessfully) remove all HTML anchors using the function above.
How do I manipulate the object as HTML through jQuery?
Update
On further inspection, I’ve realized the problem is different from what I initially thought.
My issue is I’m not able to manipulate the variable (temporaryString) as a jQuery object. For example, the following will not affect the html of the object:
$(temporaryString).find("div").remove();
So, in theory if I have the following:
temporaryString = "<span>Span Content</span><div>DIV Content</div>";
$(temporaryString).find("div").remove();
I would assume ‘temporaryString’ should now equal:
<span>Span Content</span>
since the div is removed.
Is my logic wrong? It doesn’t seem to be working.
Here’s your problem: In Javascript, strings are immutable, that means that they can’t be changed. Unless you assign something different to the variable
temporaryString, that variable isn’t going to change.When you run this code:
This is what happens:
"<span>Span Content</span><div>DIV Content</div>"is assigned totemporaryString$(temporaryString)runs, parsingtemporaryStringand creating a corresponding array-like object (the jQuery object) of html elements and returns it.temporaryStringis left unchanged..find("div")runs, finds all div elements in the result of the above step and returns them.temporaryStringis left unchanged..remove()runs, removing the elements returned by the previous step from the jQuery object.temporaryStringis left unchanged.$(temporaryString).find("div").remove()pass out of scope and are deleted by the garbage collector.temporaryStringhas still not been changed.In short, if you don’t do anything with the result of
$(temporaryString).find("div").remove(), nothing happens.If you want
temporaryStringto become"<span>Span Content</span>", you need to assign the result of all the manipulations you’ve done to the jQuery object back into thetemporaryStringvariable. The best way to do this is to create adivelement, set it’s contents totemporaryString, remove the desired elements, and assign the new contents of thedivelement back intotemporaryStringlike this:For your original question, you can try this:
Sorry for the long winded answer.