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

前端 未结 2 1168
你的背包
你的背包 2021-01-16 17:57

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

Example:
I have this code

相关标签:
2条回答
  • 2021-01-16 18:12

    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

    0 讨论(0)
  • 2021-01-16 18:24

    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

    0 讨论(0)
提交回复
热议问题