How to remove everything from body apart from one tag with perticular class with jQuery?

This will be a rather strange question. But I thought I'd give it.

Is there a way to remove everything from the body except one tag that has a specific class?

in my case it is a tag with href.

I need to "catch" the a tag and then render to the DOM only the href tag, where the p tag can be said.

<body>
 <a class="avatar_user_name" href="/product/xyz">Title</a>

...other body tags and text

<a class="avatar_user_name" href="/product/abc">Title</a>
</body>

      

and as a result I need something like this

<body>
<p>xyz</p>
<p>abc</p>
</body>

      

Thanks for any help in advance. Relationship

+2


source to share


2 answers


Not sure if this will work, but worth a try?

<script type="text/javascript>
$(document).ready(function() {

    // obtain list of links
    var a = [];
    $('a.avatar_user_name').each(function(i,e) {
        a[i] = $(this).attr('href');
    });
    // build up a new page
    $('body').empty();
    for (var i = 0, j = a.length; i < j; i++) {
        $('body').append('<p>' + a[i] + '</p>');
    } 
});
</script>

      



Let us know if this works, I would be curious if it does! Good luck!

+4


source


I can't think of any way to do this. I think the best option would be to either grab or encode the values โ€‹โ€‹of the two links in JS, remove everything inside the body, and then add the links back. This may not be the most efficient, but usually people don't remove everything inside the body of the tag.



Another option is to add a tag around everything else in the body tag (if the page structure is as simple as your example in the question). This tag does not have to be a formatting tag, but it can be a range with an ID. In this case, you just remove everything inside that tag.

-1


source







All Articles