-2

I am trying to retrieve and loop through all the elements on my page which are spans and have name tag. Any ideas?

$("span[name$='*']").each(function () {  // first pass, create name mapping               
           // Console.log(this);
            //name_map[name] = (name_map[name]) ? name + "[]" : name;
 });

<span class="col-xs-2 control-label" name="toddler">xxx</span> <-- get this
<span class="col-xs-2 control-label">xxx</span> <-- don't get this
alwaysVBNET
  • 2,950
  • 7
  • 27
  • 61

2 Answers2

4

You can just put the attribute in the selector with no value, eg [name]. Try this:

$("span[name]").addClass('foo');
.foo { color: #C00; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="col-xs-2 control-label" name="toddler">yes</span>
<span class="col-xs-2 control-label">no</span>
Satpal
  • 129,808
  • 12
  • 152
  • 166
Rory McCrossan
  • 319,460
  • 37
  • 290
  • 318
2

var arr = $("span[name]").map(function() {
  return $(this).text()
}).get();


console.log(arr)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="col-xs-2 control-label" name="toddler">xxx1</span>
<span class="col-xs-2 control-label">xxx</span>
  1. use only $('span[name]'). Means Span with name attribute
guradio
  • 15,359
  • 3
  • 33
  • 52