How can I append text into detached html

64 views Asked by At

It seems like this should be super easy, but I have not yet found a way to do it; What I am trying to do is this:

I have some html that came from a service call. The markup has tags in it like p, strong, etc. I am trying to append() a link into the last paragraph before I send the markup to the page (w angular). I have been using jQuery to attempt to get the markup like I want but so far no gold.

My code looks something like this:

var intro = row['Introduction']; // from the service call
var contents = jQuery(intro).contents().get(); // get the items within
for (var i = contents.length - 1; i > 0; i--) { // start with the last
  if (jQuery(contents[i]).context.nodeType === 3) { // is it text?
    jQuery('<a class="less">Less</a>').appendTo(contents[i]); // append
    break;
  }        
} 

This doesn't seem to be having any effect though. When I console.log(contents[i]) after appending, it's still the same. What gives?

For clarification, I have this html coming in the service:

console.log(intro);
<p>This is text</p>
<p>This is more text.</p>
<p>And even more here.</p>

And this: jQuery(intro).find('p'); gets 0 results!

What am I missing!?

Also, I don't know if this is relevant, however this code is executed within an AngularJS controller.

For a sanity check I tried this on jsfiddle (to make sure I wasn't going bonkers) https://jsfiddle.net/n094LL3s/ Apparently, find does't work with html strings!... -_-

OK, I found out I need to use $.filter('p') not find to get items that are at the root of the set.

1

There are 1 answers

1
A. Wheatman On

In your case instead of .find() you need to use .filter() like this $(text).filter('p').length. If you still want to use .find() you need to modify your HTML string a bit and put it inside <div> element (or any other container), for example like this text = '<div><p>One</p><p>Two</p><p>Three</p></div>';

And the reason of this behavior you can find in the .find() method description

Description: Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element.

Check modified fiddle here