ReplaceWith, replacing elements
The ReplaceWith () method replaces the contents of the selected element with other content.
Let's first look at an example
<!DOCTYPE HTML><HTML><Head><MetaCharSet= "Utf-8"><Metaname= "Author"content= "http://www.51texiao.cn/" /><title>No title</title><Scriptsrc= "Http://libs.baidu.com/jquery/1.9.0/jquery.js"></Script><Scripttype= "Text/javascript">$ (document). Ready (function(){ $("Button"). Click (function(){ $("P"). ReplaceWith ("<b>hello</b>"); //Replace the contents of the P element with "<b>hello</b>" }); });</Script></Head> <Body> <P>1111111111111111111111</P> <Button>Click</Button></Body></Body></HTML>
Maybe a lot of friends can not understand, let me introduce.
In jquery, there is a powerful replacement function replacewith (), which is very simple to use, such as:
The page has the following P tag
<Body> <P>Ha ha</P> <P>Ha ha</P> <P>Ha ha</P> <P>Ha ha</P> <Button>Click</Button></Body>
Replace all P tags with "# #"
<script type= "Text/javascript" > $ (document). Ready (function() { $ (" Button "). Click (function() { $ (" P "). ReplaceWith (" # # ") ; // Replace the P element with # # " }); }); </script>
Results after execution:
Replace label
With this replacewith, we can replace all P tags with a b tag, with the same content:
$ ("button"). Click (function() { $ (' P '). each (function() { $( ). ReplaceWith (' <b> ' +$ (this). html () + ' </b> ')}) ;
Results
That's a replacement!
Multi-lingual sites can be easily completed with this function
If you are developing a multi-lingual website, you can even take advantage of this feature, such as adding the I tag to the text you need to translate, and then traversing the translation substitution.
<!DOCTYPE HTML><HTML><Head><MetaCharSet= "Utf-8"><Metaname= "Author"content= "http://www.51texiao.cn/" /><title>No title</title><Scriptsrc= "Http://libs.baidu.com/jquery/1.9.0/jquery.js"></Script><Scripttype= "Text/javascript">$ (document). Ready (function(){ varTranslate={ 'Apple':'Apple', 'Computer':'PC' }; $("Button"). Click (function(){ $('I'). each (function(){ $( This). ReplaceWith (translate[$ ( This). HTML ()]); }) }); });</Script></Head> <Body> <P><I>Apple</I></P> <P><I>Computer</I></P> <Button>Click</Button></Body></Body></HTML>
ReplaceWith and ReplaceAll
The same point: they can all be two, find replacements
Different points: different writing, anyway I did not find, they two have what function on the difference.
A detailed description of jquery's replacewith () function usage