使用Javascript将span标记环绕在句子周围

使用Javascript将span标记环绕在句子周围,javascript,tags,add,Javascript,Tags,Add,我需要在我的页面上找到一个句子,并用span标记(带有类)将其包装起来 这是我的页面: <body> <h1>Home Page</h1> <p>Welcome to the homepage of the site. Enjoy your stay</p> </body> 主页 欢迎访问网站主页。祝你住得愉快 使用Javascript,我想将p内容转换为: <p><span class="mySpa

我需要在我的页面上找到一个句子,并用span标记(带有类)将其包装起来

这是我的页面:

<body>
<h1>Home Page</h1>
<p>Welcome to the homepage of the site. Enjoy your stay</p>
</body>

主页
欢迎访问网站主页。祝你住得愉快

使用Javascript,我想将p内容转换为:

<p><span class="mySpan">Welcome to the homepage</span> of the site. Enjoy your stay</p>
欢迎访问网站主页。祝你住得愉快


这是您需要做的:

  • 使用.innerHtml或jQuery.html()读取html
  • 解析数据
  • 使用.innerHtml或jQuery.html()写回数据
  • 您可以使用正则表达式和其他各种方法进行解析。。 下面是一个简单的例子

    var html = $("p").html();
    html = "<span>" + html;
    html = html.replace("homepage","homepage</span>");
    $("p").html(html);
    
    var html=$(“p”).html();
    html=”“+html;
    html=html.replace(“主页”、“主页”);
    $(“p”).html(html);
    
    下面是一个正在工作的JSFIDLE:

    如果您希望避免使用jquery,请尝试以下方法:

    <script>  
      P = document.getElementsByTagName('p');
      search = 'Welcome to the homepage';
      s = P[0].innerHTML.replace(search,'<span class="mySpan">' + search +'</span>');
      P[0].innerHTML =s;
    </script> <!-- always locate script at the end of the body -->
    </body>  
    
    
    P=document.getElementsByTagName('P');
    搜索='欢迎访问主页';
    s=P[0].innerHTML.replace(搜索“+”搜索+”;
    P[0].innerHTML=s;
    

    但是,为了增强它,您应该考虑将ID属性包含到元素中,并使用方法文档.GETelEnMyBid(“thid id”)选择此元素。.

    不清楚您是想将html元素从p改为SPAN,还是只想设置p元素的样式。@jgpATs2w基本上这就是我想要的结果:
    欢迎访问网站主页。祝您在这里过得愉快

    @Alex K:因为它没有用jquery标记,所以答案可能会有所不同。