在 Javascript 中使用正则表达式查找并更改 div
我试图首先使用正则表达式找到一个 div (因为它的类名有点动态)。
找到后,我需要将 div 放置在字段集中,因此最终输出为
<fieldset class="...">
<div class="the one I found">...</div>
</fieldset>
How can I do this in javascript?
非常感谢, 史蒂夫
I am trying to first find a div using a regular expression (since its class name is somewhat dynamic).
Once found, I then need to place the div inside of a fieldset, so I end up having a final output of
<fieldset class="...">
<div class="the one I found">...</div>
</fieldset>
How can I do this in javascript?
Much thanks,
Steve
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这对于正则表达式来说很难做到,而且是不明智的。例如,如果 div 包含其他 div 该怎么办?正则表达式无法找到正确的结束 div 标签,因为 HTML 不是正则语言。
另一方面,这是一个带有 jQuery 的简单单行代码:
它当然可以使用 vanilla Javascript DOM 来完成类似于:
您当然需要填写要放在字段集上的类,并更改 div 上的测试以确定是否需要操作它。
This is going to be difficult to do with regexes and ill-advised. For example, what if the div contains other divs? Finding the correct closing div tag is not something a regular expression can do because HTML is not a regular language.
On the other hand, this is a trivial one liner with jQuery:
It can of course be done with vanilla Javascript DOM using something like:
You of course need to fill in what class to put on the fieldset and change the test on the div to figure out if you need to manipulate it or not.
使用 jquery ,您可以尝试以下操作:
using jquery, you can try this:
不需要使用正则表达式,indexof方法就足够了。并且不需要使用jquery。 Javascript 有很好的字符串和数组函数 - 使用它们,但是 DOM 是一团糟。
No need to use regular expression, indexof method is sufficient. And no need to use jquery. Javascript has good string and array functions - use them, but the DOM is a mess.