查找具有特定文本的DOM元素并对其进行修改 [英] Finding the DOM element with specific text and modify it

查看:197
本文介绍了查找具有特定文本的DOM元素并对其进行修改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图弄清楚如何在原始javascript(无jQuery等)中找到具有特定文本的元素并修改该文本。

I'm trying to figure out how to, in raw javascript (no jQuery, etc.), find an element with specific text and modify that text.

我对解决方案的第一个化身...还不够。我所做的基本上是:

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;

我天真地以为我成功实现了色彩鲜艳,特别是因为它是如此简单。因此,然后我在示例中添加了一个图片,并认为我可以每5秒检查一次(因为此字符串可以动态输入DOM)...并且图片每5秒闪烁一次。

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.

糟糕。

因此,必须有一种正确的方法。

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.

现在,总有递归地搜索子级,直到找到最深的子级为止。我想避免这种情况。即便如此,我还是对将将innerHTML更改为其他内容是否是更新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.

那么,正确的搜索方法是什么通过DOM获取字符串?那么更新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?

推荐答案


现在,总有递归地搜索孩子,直到找到最深的孩子为止。我想避免。

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.

旧计时器magno磁带,记录下来,聆听,冥想。

Old-timer magno tape, record, listen, meditate.

顺便说一句,请参阅: James Padolsey的博客

Btw, see: Find and replace text with JavaScript on James Padolsey's blog

这篇关于查找具有特定文本的DOM元素并对其进行修改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆