Javascript 查找具有特定文本的 DOM 元素并对其进行修改
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6132074/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Finding the DOM element with specific text and modify it
提问by rk1s
I'm trying to figure out how to, in raw javascript (no jQuery, etc.), find an element with specific text and modify that text.
我试图弄清楚如何在原始 javascript(没有 jQuery 等)中找到具有特定文本的元素并修改该文本。
My first incarnation of the solution... is less than adequate. What I did was basically:
我的解决方案的第一个化身......还不够。我所做的基本上是:
var x = document.body.innerHTML;
x.replace(/regular-expression/,"text");
document.body.innerHTML = x;
Naively I thought I succeeded with flying colors, especially since it was so simple. So then I added an image to my example and thought I could check every 5 seconds (because this string may enter the DOM dynamically)... and the image flickered every 5 seconds.
我天真地以为我成功了,特别是因为它是如此简单。然后我在我的例子中添加了一个图像,并认为我可以每 5 秒检查一次(因为这个字符串可能会动态进入 DOM)......并且图像每 5 秒闪烁一次。
Oops.
哎呀。
So, there has to be a correct way to do this. A way that specifically singles out a specific DOM element and updates the text portion of that DOM element.
所以,必须有一个正确的方法来做到这一点。一种专门挑出特定 DOM 元素并更新该 DOM 元素的文本部分的方法。
Now, there's always "recursively search through the children till you find the deepest child with the string" approach, which I want to avoid. And even then, I'm skeptical about "changing the innerHTML to something different" being the correct way to update a DOM element.
现在,总是有“递归搜索孩子,直到找到最深的孩子”的方法,我想避免这种方法。即便如此,我还是怀疑“将 innerHTML 更改为不同的东西”是否是更新 DOM 元素的正确方法。
So, what's the correct way to search through the DOM for a string? And what's the correct way to update a DOM element's text?
那么,在 DOM 中搜索字符串的正确方法是什么?更新 DOM 元素文本的正确方法是什么?
采纳答案by gblazex
Now, there's always "recursively search through the children till you find the deepest child with the string" approach, which I want to avoid.
现在,总是有“递归搜索孩子,直到找到最深的孩子”的方法,我想避免这种方法。
I want to search for an element in an unordered random list. Now, there's a "go through all the elements till you find what you're looking for approach", which I want to avoid.
我想在无序随机列表中搜索一个元素。现在,有一种“遍历所有元素,直到找到所需的方法”,我想避免这种情况。
Old-timer magno tape, record, listen, meditate.
老式磁带,记录,聆听,冥想。
Btw, see: Find and replace text with JavaScripton James Padolsey'sblog
顺便说一句,请参阅:在James Padolsey 的博客上使用 JavaScript 查找和替换文本
回答by RobG
Don't use innerHTML with a regular expression, it will almost certainly fail for non-trivial content. Also, there are still differences in how browsers generate it from the live DOM. Replacing the innerHTML will also remove any event listeners added as element properties (i.e. like element.onclick = fn
).
不要将innerHTML 与正则表达式一起使用,它几乎肯定会因非平凡的内容而失败。此外,浏览器如何从实时 DOM 生成它仍然存在差异。替换innerHTML 也将删除作为元素属性添加的所有事件侦听器(即像element.onclick = fn
)。
It is best if you can have the string enclosed in an element with an attribute or property you can search on (id, class, etc.) but failing that, a search of text nodes is the best approach.
最好是将字符串包含在具有可以搜索的属性或属性(id、class 等)的元素中,但如果失败,则搜索文本节点是最好的方法。
Edit
编辑
Attempting a general purpose text selection function for an HTML document may result in a very complex algorithm since the string could be part of a complex structure, e.g.:
尝试对 HTML 文档使用通用文本选择函数可能会导致非常复杂的算法,因为字符串可能是复杂结构的一部分,例如:
<h1>Some <span class="foo"><em>s</em>pecial</span> heading</h1>
Searching for the string "special heading" is tricky as it is split over 2 elements. Wrapping it another element (say for highlighting) is also not trivial since the resulting DOM structure must be valid. For example, the text matching "some special" in the above could be wrapped in a span but not a div.
搜索字符串“特殊标题”很棘手,因为它被分成 2 个元素。将它包装到另一个元素(比如突出显示)也不是微不足道的,因为生成的 DOM 结构必须是有效的。例如,上面匹配“some special”的文本可以包含在span中,但不能包含在div中。
Any such function must be accompanied by documentation stating its limitations and most appropriate use.
任何此类功能都必须附有说明其限制和最适当用途的文件。
回答by patorjk
Edit: Changed querySelectorAll to getElementsByTagName from RobG's suggestion.
编辑:从 RobG 的建议中将 querySelectorAll 更改为 getElementsByTagName。
You can use the getElementsByTagName function to grab all of the tags on the page. From there, you can check their children and see if they have any Text Nodes as children. If they do, you'd then look at their text and see if it matches what you need. Here is an example that will print out the text of every Text Node in your document with the console object:
您可以使用 getElementsByTagName 函数来获取页面上的所有标签。从那里,您可以检查他们的孩子,看看他们是否有任何文本节点作为孩子。如果他们这样做了,你就会查看他们的文本,看看它是否符合你的需要。这是一个示例,它将使用控制台对象打印出文档中每个文本节点的文本:
var elms = document.getElementsByTagName("*"),
len = elms.length;
for(var ii = 0; ii < len; ii++) {
var myChildred = elms[ii].childNodes;
len2 = myChildred.length;
for (var jj = 0; jj < len2; jj++) {
if(myChildred[jj].nodeType === 3) {
console.log(myChildred[jj].nodeValue);
// example on update a text node's value
myChildred[jj].nodeValue = myChildred[jj].nodeValue.replace(/test/,"123");
}
}
}
To update a DOM element's text, simple update the nodeValue property of the Text Node.
要更新 DOM 元素的文本,只需更新文本节点的 nodeValue 属性。
回答by alex
Forget regular expressions.
忘记正则表达式。
Iterate over each text node (and doing it recursively will be the most elegant) and modify the text nodes if the text is found. If just looking for a string, you can use indexOf()
.
迭代每个文本节点(递归执行将是最优雅的)并在找到文本时修改文本节点。如果只是寻找一个字符串,你可以使用indexOf()
.
回答by Ibu
x.replace(/regular-expression/,"text");
will return a value so
将返回一个值
var y = x.replace(/regular-expression/,"text");
now you can assign new value.
现在您可以分配新值。
document.body.innerHTML = y;
Bu you want to think about this, you dont't want to get the whole body just to change one small piece of code, why not get the content of a div or any element and so on
但是你要考虑这个,你不想为了改变一小段代码就得到整个body,为什么不得到一个div的内容或者任何元素等等
example:
例子:
<p id='paragraph'>
... some text here ...
</p>
now you can use javascript
现在你可以使用javascript
var para = document.getElementById('paragraph').innerHTML;
var newPara = para.replace(/regex/,'new content');
para.innerHTML = newPara;
This should be the simplest way.
这应该是最简单的方法。