How to replace HTML tag text

I don't know what to call it, but let me call it a semi-inner text.

Example

<div id='myDiv'>
    This is the semi-inner text
    <div id='other'></div>
    This is the semi-inner text
<div>

I want to remove / replace those This is the semi-inner textwith jquery.

How can i do this?

+3
source share
6 answers

If you only care about child nodes ...

$('#myDiv').contents().filter(function() {
    return this.nodeType == 3
}).each(function() {
    this.data = this.data.replace(/This is the semi-inner text/g, 'swapped');
});​

jsFiddle .

If you want to check all descendant nodes, make the recurse function when it detects the node ( this.nodeType == 1) element .

+3
source
$('#myDiv')
    .contents()
    .filter(function() {
        return this.nodeType == 3;
    })
    .each(function() {
        $(this).remove();
    });
+2
source

() nodeType, 3, :

$('#myDiv').contents().filter(function() {
    return this.nodeType == 3;
}).remove();
+1

$("#other").html("your code");

span id

0

- :

<div id='myDiv'>
    <span id="myInnerText">This is the semi-inner text</span>
    <div id='other'></div>
    This is the semi-inner text
<div>

:

$("#myInnerText").text("replacement text");
0

:

target_div = $("#myDiv")
  reg_exp  = /This is the semi-inner text/g;
  new_text = "some other text"

  target_div.html(
    target_div.html()
      .replace(
        new RegExp(reg_exp),
        new_text)
        );
 });

0
source

All Articles