Home > Net >  Get multiple data element class and put in DOM elmenent
Get multiple data element class and put in DOM elmenent

Time:03-15

I want when I click on an element - another element gets the class name of the attribute that I clicked:

var countryElements = document.getElementById('items').childNodes;
  var countryCount = countryElements.length;
  for (var i = 0; i < countryCount; i  ) {
    countryElements[i].onclick = function() {
      console.log('My Data Name: '   this.getAttribute('data-name'));
    }
  }
  
  $('#items .check').click(function () {
    var linkHref = $(this).data('name');
    $('#provinceInfo').html(linkHref);
    $('#provinceInfo').addClass(linkHref);
});
#provinceInfo{
background-color:#f4f4f4;
padding:30px;
margin-bottom:10px
font-weight:700;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="provinceInfo"></div>
<div id="items">
  <div  data-name="london">United Kingdom</div>
  <div  data-name="berlin">Germany</div>
  <div  data-name="paris">France</div>
</div>

How to make it show only the current class? And not all that clicks? Scenario: I click on Germany - the berlin class is set, I click on France - the paris class is set, and the berlin is deleted. Thank you.

CodePudding user response:

Change:

$('#provinceInfo').addClass(linkHref);

to:

$('#provinceInfo').removeClass().addClass(linkHref);

.removeClass() without any arguments will remove all classes from the matched elements.

var countryElements = document.getElementById('items').childNodes;
  var countryCount = countryElements.length;
  for (var i = 0; i < countryCount; i  ) {
    countryElements[i].onclick = function() {
      console.log('My Data Name: '   this.getAttribute('data-name'));
    }
  }
  
  $('#items .check').click(function () {
    var linkHref = $(this).data('name');
    $('#provinceInfo').html(linkHref);
    $('#provinceInfo').removeClass().addClass(linkHref);
});
#provinceInfo{
background-color:#f4f4f4;
padding:30px;
margin-bottom:10px
font-weight:700;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="provinceInfo"></div>
<div id="items">
  <div  data-name="london">United Kingdom</div>
  <div  data-name="berlin">Germany</div>
  <div  data-name="paris">France</div>
</div>

CodePudding user response:

You can use attr instead of addclass and add your default class to it so you don't miss it.

$('#items .check').click(function () {
    var linkHref = $(this).data('name') ' check';
    $('#provinceInfo').html(linkHref);
    $('#provinceInfo').attr('class', linkHref);
});
  • Related