简体   繁体   中英

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:

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

From javascript:

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

You can also use psuedo selector :contains, with the jQuery library .

Example 2

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

http://jsfiddle.net/9z5du/

Example 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:

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. You might have to trim the text first before you compare it.

If the HTML is as shown in your post,

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

is even more elegant.

The MDN documentation about the DOM might be helpful.

If you can modify the HTML then adding an ID and using getElementById would be the better option.

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]);
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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