scrippyfingers scrippyfingers - 1 year ago 91
HTML Question

Writing a conditional to add an attribute

I am trying to add an attribute to an element that is called dynamically using the select2 jQuery library.

When the page is open a

span
element is added with a class of
select2-container
, I need to add a unique
data-bactmln
attribute value to each
span
element with the
select2-container
class.

Since the
span
is nested in a
div
and each
div
is set up as such:

<div class="fieldset cr">
...
<span class="select2-container"></span>
</div>


can I target the
span
in that
div
to add the specific attribute value?

I tried using a conditional, however I'm having trouble getting it to work.

if($('.cr')){
$('.select2-container').attr('data-bactmln', 'CR_FeaturesDropdown');
}

Answer Source

try to change your condition to

if($('.cr').length > 0){
  $('.select2-container').attr('data-bactmln', 'CR_FeaturesDropdown');
}

if $('.cr') has a value it its length will be bigger than 0

if($('.cr').length > 0){
  $('.select2-container').attr('data-bactmln', 'CR_FeaturesDropdown');
  console.log($('.select2-container').data());
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="fieldset cr">
   ...
   <span class="select2-container"></span>
</div>

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