How do I remove HTML and special charaters using jQuery?

后端 未结 6 1012
走了就别回头了
走了就别回头了 2021-01-29 11:44

So what I want to do is remove all of the HTML table tag elements, leaving the link tags alone.


&l         
6条回答
  •  萌比男神i
    2021-01-29 12:19

    Update: Woah, you completely changed the question with your edit. Completely.

    You can process the tables in your new question, putting all the links contained by the table into a single new paragraph, like this:

    $('table').each(function() {
      var $thisTable = $(this),
          links = $thisTable.find('a'),
          newPara;
      $thisTable.parent().append($("

    ").append(links)); $thisTable.remove(); });

    Live example

    Or if you want each link in its own paragraph (probably better):

    $('table').each(function() {
      var $thisTable = $(this),
          $parent = $thisTable.parent(),
          links = $thisTable.find('a');
      links.each(function() {
        $parent.append($("

    ").append(this)); }); $thisTable.remove(); });

    Live example


    Original answer, now irrelevant:

    You can use empty:

    $(".headlines").empty();
    

    ...to completely empty the matching elements.

    Or if you want to selectively remove just the at the beginning, you can use html and pass in a function:

    $(".headlines").html(function(index, html) {
        if (html.substring(0, 1) === "•") {
            html = html.substring(1);
        }
        return html;
    });
    

    Or perhaps the * and any whitespace after it:

    $(".headlines").html(function(index, html) {
        return html.replace(/^• */, '');  // A `•` at start of string
                                          // followed by zero or more spaces
    });
    

    Live example

    ...but don't do either of the latter ones that if the headlines elements will have complex, nested structures with event handlers on them, etc. (it's fine for basic cells, though).

提交回复
热议问题