Replacing Text in a child under parent DIV through

2019-02-25 18:54发布

问题:

I want to change text of (Access denied. Please Login or Register.) to "You are not authorized to access" in the following code:-

<div class="messages error">
<h2 class="element-invisible">Error message</h2>
Access denied. Please Login or Register.
</div>

I tried using the following code in on Ready Function, but it isn't working correctly.

$("div.messages").text(function () {
        console.log($(this).text());
        return $(this).text().replace("Access denied. Please Login or Register.", "You are not authorized to access"); 
    });

Thanks.


Is there anyother way to do that? It gives me the error of

Uncaught TypeError: Cannot set property 'nodeValue' of undefined ... 

回答1:

$("div.messages h2")
      .prop('nextSibling')
      .nodeValue = "You are not authorized to access";

http://jsfiddle.net/ZwLKZ/

$("div.messages").contents().filter(function() {
     return this.nodeType === 3 && $.trim(this.nodeValue) !== ''; 
}).get(0).nodeValue = "You are not authorized to access";