0

I have to put a lot of data-element with the same content in multiple div.
How to define this content in a script in order to write it one time ?
I think I have to use a simple script but I can't find the solution. Thanks.

<div class="one" data-text"EXAMPLE"></div>
<div class="two" data-text"EXAMPLE"></div>  
<div class="three" data-text"EXAMPLE"></div>
<div class="four" data-text"EXAMPLE"></div>
<div class="five" data-text"EXAMPLE"></div>
5
  • 1
    What divs does this get applied to? What's the criteria Commented Sep 9, 2014 at 14:21
  • Couldn't you just use jQuery attr ? Commented Sep 9, 2014 at 14:21
  • 1
    $("div").attr("data-text","Example"); Commented Sep 9, 2014 at 14:22
  • What's going to consume this attribute? Commented Sep 9, 2014 at 14:23
  • In order to apply some :before and :after properties for a typography effect. Commented Sep 9, 2014 at 14:36

3 Answers 3

2

if you add a shared class to all of them you can target that class and add a data-attr. If you target just the div it's going to add it to every div on the page.

$(".target").attr("data-text", "TEXT");

JSFIDDLE

Sign up to request clarification or add additional context in comments.

Comments

2

Add some additional class to all your divs. Like

<div class="one mydata" data-text"EXAMPLE"></div>
<div class="two mydata" data-text"EXAMPLE"></div>

etc.

then you can execute the following script :

$(".mydata").attr("data-text", "OTHER EXAMPLE");

Comments

1

You have here the ways to use it:

jQuery (correct method, might not map to 'real' HTML attributes):

$('#element').data('value_to_set',value);
value=$('#element').data('value_to_get');

jQuery (other method):

$('#element').attr('data-value_to_set',value);
value=$('#element').attr('data-value_to_get');

Pure Javascript (method 1, for modern browsers and IE11+):

document.getElementById('#element').dataset.value_to_set=value;
value=document.getElementById('#element').dataset.value_to_get;

Pure Javascript (method 2, for browsers with Javascript):

document.getElementById('#element').setAttribute('data-value_to_set',value);
value=document.getElementById('#element').getAttribute('data-value_to_get');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.