NeedH8
NeedH8

Reputation: 482

How to use attribute and insert it as element jquery

Is it possible to insert, f.e. to "span", an attribute like this.

<span data-text="Hello world"></span>

If the event reaches its condition, then script takes information from "data-text" and inserts it into "span".

So, resulting span will be like

<span data-text="Hello world">Hello world</span>

Upvotes: 3

Views: 46

Answers (1)

Tushar
Tushar

Reputation: 87203

Yes, you can use text as follow

$('span[data-text]').text(function() {
    return $(this).data('text');
});
  1. $('span[data-text]') will select all the <span> elements having data-text attribute present on them
  2. text() with callback function is used to iterate over all the matched elements and update their respective innerText. You can also use html() instead of text().
  3. $(this).data('text') will retrieve the data-text attribute value of the current($(this)) element and returning it from the function will update the innerText.

Demo

$('span[data-text]').text(function() {
  return $(this).data('text');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<span data-text="Hello world"></span>
<span data-text="GoodBye World!"></span>
<span data-text="Is it Working?"></span>

Upvotes: 1

Related Questions