Kajcioch Kajcioch - 2 months ago 9
jQuery Question

What are append(); and prepend(); limitations?

$("a").contents().each(function(){
this.nodeValue = $.trim($(this).text()).replace("[Hello]","");
$(this).prepend("Pre").append("End");
});


I want a
[Hello]
to be cut from every
a
, but at the same time I want a
prepend()
and
append()
functions to work. In fact, a
replace()
function works perfectly, but the other two fails. I get no errors in console though.

Please keep in mind that
nodeType
of
$(this)
is
3
so it's a
text
type.

Why aren't
append()
and
prepend()
working?

Answer

jQuery.prepend:

The .prepend() method inserts the specified content as the first child of each element

But textNodes do not have children, so you cannot prepend or append elements into them.

But you can use jQuery.before and jQuery.after to insert content before and after the textNode:

$("a").contents().each(function() {
  this.nodeValue = $.trim($(this).text()).replace("[Hello]", "");
  $(this).before("Pre").after("End");
});

But you need to take care because for an <a>some text</a> the some text could consist out of multiple text nodes, normally this should not be the case, but you should be award of that.