I have an element on page with title="class className dataAttr". I want to create a jQuery code which add className to class="className" and dataAttr to data-icon="dataAttr" from title. Here my code:
<script> $(document).ready(function () { $("[title*='class']").addClass(function () { return $(this).attr('title'); }).attr('data-icon', function () { str = $(this).attr("title"); str = str.replace('class', ''); return str }).removeClass('class').removeAttr('title'); }); </script>
But this script add className and dataAttr together to class and data-icon too. I think that there will be some condition for space or symbol between className and dataAttr to add it separately. I don't know how to do it. Do you know some solutions about that? I hope you understood my problem.
The following snippet works:
$( document ).ready(function() { $("[title*='class']").each(function() { var title = $(this).attr('title'); var titleArray = title.split(" "); $(this).addClass(titleArray[1]); $(this).attr("data-icon", titleArray[2]); $(this).removeAttr('title'); }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <p title="class className dataAttr">test</p>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.