dublintech
dublintech

Reputation: 17795

Selecting a DOM element from a JQuery object?

Consider the JQuery object myDiv

myDiv = $('<div class="question"><b><span>MyText</span></b></div>');

How do I select the text with within the span tags so that I can do something like:

myElement.text = 'New text';

Upvotes: 0

Views: 58

Answers (3)

asgoth
asgoth

Reputation: 35829

Like this:

$('.question, span').text('new text');

Upvotes: 1

David Thomas
David Thomas

Reputation: 253496

If you don't know beforehand what the element will be, but it will always be the most deeply-nested:

var myDiv = $('<div class="question"><b><span>MyText</span></b></div>'),
    nested = myDiv.find(':last-child').last();
nested.text('my new text');

JS Fiddle demo.

Upvotes: 0

Adam Rackis
Adam Rackis

Reputation: 83376

Like this:

$('span', myDiv).text('New text');

That selects the span from within your myDiv object, and sets the text accordingly.

Here's a live demo

Upvotes: 2

Related Questions