AndroidDev AndroidDev - 1 year ago 41
jQuery Question

Search all attributes in the entire DOM for text

I need to search the entire DOM for text but want to limit the search only to properties (attributes). I am only aware of searching for properties if you already know their names. Example:

$(document).find("[name='description']");


But I want something like:

$(document).find("[*='description']");

Answer Source

I'm not sure if this is the prettiest of solutions since it requires you to loop through all elements on the page, but you could check the attributes property of all elements.

$(function() {
  $("*").each(function() {
    var $el = $(this);
    $.each(this.attributes, function() {
      if (this.value=='description') {
        console.log('Found for attribute "'+this.name+'".');
        console.log('Text: '+$el.text());
      }
    });
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div data-test1="description">test1</div>
<div data-test2="bla" id="description">test2</div>
<div data-test3="bla bla" class="description">test3</div>
<div data-test4="description" class="description">test4</div>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download