访问元素<pre> with jQuery

时间:2019-05-31 11:22:38

标签: jquery

I've this code:

<div class="modal-body">
    <p class="m-b-lg">...</p>
    <div class="text-right fz-sm">
        <a href="#" data-action="copy-link">Copy link</a>
    </div>
    <pre>
        Lorem ipsum...
    </pre>
</div>

How can I access to <pre> tag ?

What I've tried:

$('[data-action="copy-link"]').on('click', function(event) {
    var code = $(this).find('pre').css('color', 'red');
});

Thanks.

2 个答案:

答案 0 :(得分:0)

You have to add .closest('.modal-body') since your pre is not a child off data-action="copy-link"

Also, please note that var code = makes little sense to in front, at the current state.

$('[data-action="copy-link"]').on('click', function(event) {
    $(this).closest('.modal-body').find('pre').css('color', 'red');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="modal-body">
    <p class="m-b-lg">...</p>
    <div class="text-right fz-sm">
        <a href="#" data-action="copy-link">Copy link</a>
    </div>
    <pre>
        Lorem ipsum...
    </pre>
</div>

答案 1 :(得分:0)

Below code is working, try this

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<script>
    $(document).ready(function(){
    $('[data-action="copy-link"]').on('click', function(event) {
        var code = $('.modal-body pre').css('color', 'red');
    });
    })
</script>
<div class="modal-body">
    <p class="m-b-lg">...</p>
    <div class="text-right fz-sm">
        <a href="javascript:void(0);" data-action="copy-link">Copy link</a>
    </div>
    <pre>
        Lorem ipsum...
    </pre>
</div>