Question

I'm currently trying to use jQuery to change the text of a number of elements to the value of a specific data-attribute.

For example:

index.html
----------
<h1 data-change="text2">text1</h1>
<p data-change="paragraph2">paragraph1</p>

I want to change 'text1' to 'text2' and 'paragraph1' to 'paragraph2' (the value of data-change for that specific element).

How would I go about doing this?

I assumed I would be able to 'select' all of the elements with the data-attribute 'data-change' and then just do a simple $(this).text($(this).data('change')); or something.

Was it helpful?

Solution

You can do this:

$('[data-change]').each(function(){
    $(this).text($(this).data('change'));
});

You can iterate over the elements and change its text.

OTHER TIPS

.text method could accept a callback function.

$('[data-change]').text(function() {
  return $(this).data('change');
});

How would you like this~

-html-

   <select id="" name="" class="input_select">

          <option value="text2" selected="selected">text2</option>
           <option value="paragraph2">paragraph2</option>
   </select>

  <h1 class="text2">text1</h1>
   <p class="paragraph2">paragraph1</p>
 </pre>

-js- $(document).ready(function(){

$('.input_select').change(function(){ var valitem = $(this).val() if (valitem == 'text2') { $('.text2').text(valitem) }else{ $('.paragraph2').text(valitem) } }) });
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top