Daft
Daft

Reputation: 10964

Replace text with my own - jQuery

This is part of the output dynamically generated by a large page of jQuery. The text inside the spans is generated inside an external script I dont have access to. I want to replace that with my own text.

How could I do that?

    <div class="questionDiv">
        <div class="innerQuestionDiv" id="firstQuestion">
            <span class="question">
                THIS IS THE FIRST QUESTION
            </span>
        </div>
     </div>

     <div class="questionDiv">
        <div class="innerQuestionDiv" id="secondQuestion">
            <span class="question">
                THIS IS THE SECOND QUESTION
            </span>
        </div>
     </div>

Maybe somthing like this...

     //TO REMOVE EXISTING TEXT
     $('#firstQuestion').innerhtml('');
     //AND REPLACE
     $('#firstQuestion').innerhtml('<span class="question">MY QUESTION</span>')

Upvotes: 2

Views: 97

Answers (4)

Cᴏʀʏ
Cᴏʀʏ

Reputation: 107498

First you need to identify which parent you're working with. In this example I've chosen the firstQuestion div. Then I expanded the selector to target the child span, whose class name is "question". Once you have the span element, use jQuery's text() function to updates its contents (if you're just updating it with new text):

$('#firstQuestion .question').text('your new text');

If you're going to add HTML content, use html() instead:

$('#firstQuestion .question').html('<strong>your new text</strong>');

Alternatively, you can just replace the entire contents of the div as you were attempting in your second code snippet:

$('#firstQuestion').html('<span class="question">MY QUESTION</span>');

Upvotes: 4

Rion Williams
Rion Williams

Reputation: 76547

You would just need to preface the ID of your ID with the '#' symbol to denote a match by ID and then you could use the .html() function to handle your replacement :

 //Removes the contents of your element
 $("#firstQuestion").html('');

 //Updates the contents
 $("#firstQuestion").html("NEW VALUE");

It should be noted that you could use the .text() function as well, however it will not format explicit HTML tags if they are entered.

Upvotes: 3

Suresh Atta
Suresh Atta

Reputation: 121998

Your Jquery selector is Invalid

   $('#firstQuestion').html('<span class="question">MY QUESTION</span>');

You should either use # (for ID's) or . for class.

Upvotes: -1

Praveen
Praveen

Reputation: 56501

$('firstQuestion').innerhtml('');  //WRONG and missed # for id selectors
$('#firstQuestion').innerHTML('');  //Correct

You can use .text()/.html() in jQuery

$('#firstQuestion').html('');
$('#firstQuestion').html('MY QUESTION');

Upvotes: 0

Related Questions