Question

I want to get all elements in an HTML Dom, which have any attribute with the a specific value.

For Example -

<ul style="width:150px;" id="RadioButton1">
   <li style="width:150px;"><input type="radio" name="RadioButton1"><label>Option 1</label></li>
   <li style="width:150px;"><input type="radio" name="RadioButton1"><label>Option 2</label></li>    
   <li style="width:150px;"><input type="radio" name="RadioButton1"><label>Option 3</label> </li>
</ul>

I want to get all elements which contains "RadioButton1" in any attribute. Means i want to select UL and all three RadioButtons.

Note: Above HTML i used UL-LI structure, but the real scenario it's too much different. So please don't give answer in completely favor of UL-LI. I want global solution.

There are any selector exist to select all type of attribute?

Is it possible to select elements with in this approach?

Bunch of Thanks in advance...!!!

Était-ce utile?

La solution

It can be done by filtering each element and checking its attributes:

Fiddle

var elements = $('*').filter(function () {
    return $(this.attributes).filter(function(){
        return this.nodeValue == 'RadioButton1'; 
    }).length;
});

Autres conseils

Try this:

$("*").each(function() { //check all elements inside DOM
    var elem = $(this);
  $.each(this.attributes, function() {
      if(this.value=='RadioButton1'){
          console.log(elem); //your code goes here. elem is nothing but element 
                               //with value RadioButton1 in any attribute
      }
  });
});

NOTE: check console for elements.

DEMO

The attributes property contains them all:

$(this).each(function() {
  $.each(this.attributes, function() {
    // this.attributes is not a plain object, but an array
    // of attribute nodes, which contain both the name and value
    if(this.specified) {
      if(this.value == 'RadioButton1')
      {
           alert(this.name);
      }
    }
  });
});
$("input[name='RadioButton1'],ul[id='RadioButton1']")

$('[name="RadioButton1"]') will select all items that have "RadioButton1" as their name attribute.

$('[id="RadioButton1"]') will select all items that have "RadioButton1" as their id attribute. Keep in mind that in case of ID attributes, there should only be one item with any given ID.

$('[name="RadioButton1"],[id="RadioButton1"]') will give you the combined list.

Keep in mind that an item that has both the ID and Name attribute set to "RadioButton1" will be added twice.

If there is a third attribute on which you want to search, just add that one to the comma-separated list of selectors.

To achieve this you should play with data-types="RadioButton"

And then using

$('input[data-types=RadioButton]')
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top