Reputation:
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.
Upvotes: 1
Views: 2705
Reputation: 11
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) } }) });
Upvotes: 0
Reputation: 160843
.text
method could accept a callback function.
$('[data-change]').text(function() {
return $(this).data('change');
});
Upvotes: 2
Reputation: 59232
You can do this:
$('[data-change]').each(function(){
$(this).text($(this).data('change'));
});
You can iterate over the elements and change its text.
Upvotes: 2