简体   繁体   English

使用Javascript,根据开始标记和结束标记之间的文本,获取元素的方法是什么?

[英]Using Javascript, what is the method to get an element, based on the text between the opening and closing tags?

I'm a beginner, and couldn't find the answer after searching. 我是一个初学者,搜索后找不到答案。

In my example, I'm looking for an 在我的示例中,我正在寻找

<a href="bla" onclick="dah">some text here</a>

I'd want to find this particular element, so I can do stuff with it. 我想找到这个特殊的元素,所以我可以做一些事情。

Edit: The only thing I know that's unique about the element for sure, is the text "some text here", that's why I want to find it based on that. 编辑:我唯一确定的关于元素的唯一确定的事情是文本“此处有一些文本”,这就是为什么我想以此为基础查找它。

Put id on the element: 将id放在元素上:

<a href="bla" onclick="dah" id='myEl'>some text here</a>

From javascript: 从javascript:

var myEl = document.getElementById('myEl') // gives the element

You can also use psuedo selector :contains, with the jQuery library . 您还可以在jQuery库中使用psuedo选择器:contains。

Example 2 例子2

$('div:contains("test")').css('background-color', 'red');​

http://jsfiddle.net/9z5du/ http://jsfiddle.net/9z5du/

Example 2 例子2

<script>
    $("div:contains('John')").css("text-decoration", "underline");
</script>

If you know that the element is a link, you can first call getElementsByTagName [docs] to narrow down your search: 如果您知道该元素是一个链接,则可以首先调用getElementsByTagName [docs]来缩小搜索范围:

var elements = document.getElementsByTagName('a');

Then you have to iterate over the elements and test which one contains the next you are looking for: 然后,您必须遍历元素并测试其中一个包含正在寻找的下一个:

var element = null;
for(var i = 0, l = elements.length; i < l; i++) {
    if(elements[i].innerHTML === 'some text here') {
        // found the element
        element = elements[i];
        break;
    } 
}

if(element) {
    // found the element, lets do something awesome with it
}

There are multiple ways to get the content of an element, using Node#innerText (IE) or Node#textContent (W3C) is another option. 获取元素内容的方法有多种,另一种选择是使用Node#innerText (IE)或Node#textContent (W3C)。 You might have to trim the text first before you compare it. 在比较之前,可能需要先修剪文本。

If the HTML is as shown in your post, 如果HTML如您的帖子所示,

if(elements[i].firstChild || elements[i].firstChild.nodeValue)

is even more elegant. 更优雅。

The MDN documentation about the DOM might be helpful. 有关DOMMDN文档可能会有所帮助。

If you can modify the HTML then adding an ID and using getElementById would be the better option. 如果可以修改HTML,则添加ID并使用getElementById将是更好的选择。

Try this 尝试这个

function getit()
{
  var elems = document.getElementsByTagName('a');

  for(var i=0; i<elems.length; i++)
  {
     var text = elems[i].childNodes[0] != null ? elems[i].childNodes[0].nodeValue : '';

     if(text == "some text here")
       doSomethingWith(elems[i]);
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM