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

前端 未结 2 1171
你的背包
你的背包 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

提交回复
热议问题