-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
  • 3,150
  • 8
  • 32
  • 65

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
  • 132,252
  • 13
  • 159
  • 168
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
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,524
  • 4
  • 36
  • 57