How to add text from span tag to data-attr by jQuery?

放肆的年华 提交于 2019-12-02 18:13:47

问题


How to add text from span tag to data-attr?

Example:
I have this code

<div class="clearfix colelem" id="u92-5"><!-- content -->
     <p>Icon<span id="u92-2">iconsymbol</span></p>
    </div>

And I want to add iconsymbol to data-attr="iconsymbol" of the same element like a:

<div class="clearfix colelem" id="u92-5" data-attr="iconsymbol"><!-- content -->
         <p>Icon<span id="u92-2">iconsymbol</span></p>
        </div>
Yes and it will be with all elements which has a title="icon"

<script>	
    $( document ).ready(function() {
	    $("[title*='icon']").attr('data-attr',function(){ 
   // I don't know
        }).removeAttr('title');
    });
</script>

Do you know how to do it? So I know it is very simple but I am new in jquery and I need in your help.
I hope you understood my question.


回答1:


Here is an example that should work for you. There is probably a few ways you can pull this off, but this should hopefully get you started. Please see the attached JSFiddle to see this example in action

$(function() {
    $('[title*="icon"] span').each(function(){
        $(this).parent().closest('div').attr('data-attr', $(this).text())
    });
});

Here is another way you can do this as well

$('[title*="icon"]').each(function(){
    $(this).attr('data-attr', $(this).children().closest('span').text());
});

JSFiddle Example




回答2:


Your <div>s should have attribute title="icon"

You are using a callback to attr() function, so return the value which you need to set inside the function using .text().

$(document).ready(function () {
    $("[title='icon']").attr('data-attr', function () {
        return $(this).find('span').text();
    }).removeAttr('title');
});

Demo



来源:https://stackoverflow.com/questions/29589398/how-to-add-text-from-span-tag-to-data-attr-by-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!