lernyoung lernyoung - 1 year ago 61
jQuery Question

Append to an element inside a set of string

How do I append to an element inside a string. Can javascript do this?

I have edited my question for some reason


var trymeor = "<div class='me'><article><div class='special'></div></article></div>";
console.log($(trymeor).find('.special').append('Hello, am testing'));

So that variable tymeor will now become like this:

var trymeor = "<div class='me'><article><div class='special'>Hello, am testing </div></article></div>";

Thank you.

Answer Source

What you have is the correct approach, but the DIV is the only element, and find finds descendant elements, so you just wanted

var trymeor  = "<div class='me'></div>";
var $element = $(trymeor).text('Hello, am testing');
console.log( $element.get(0).outerHTML );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Note that you can create elements with jQuery as well

$('<div />', {'class' : 'me', text : 'Hello, am testing'})

If you want to access a root element with a selector, you can also use filter

var trymeor = "<div class='me'></div>";
var $element = $(trymeor);

$element.filter('.me').text('Hello, am testing');

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

If you wanted to target both descendants and root elements, you can wrap your HTML is container

var trymeor = "<div class='me'></div>";
var $element = $('<div />', {html : trymeor});

$element.find('.me').text('Hello, am testing');

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download