简体   繁体   中英

remove specific html tag with its content by js

here is my html codes where I want to change.

<table>
    [some table row]
    <tr class="high">
        some text
    </tr>
    [many more table row]
</table>

now I want to remove the following tag with its class and inner contents. is there any way to remove it using replace command like "replace(/pattern/, '')".

please write a little details about how you write the patterns.

If your table have an id, say table_id you can do it by pure ,

var table = document.getElementById('table_id');
for(var i=0; i<table.rows.length;i++){
    if(table.rows[i].className=="high"){
        table.deleteRow(i);
        break;
    }
}

You might want to take a look at the jQuery library. It offers a lot of ways to search and alter html code.

You can search for css patterns and remove the element:

jQuery("tr.high").remove();

http://www.jquery.com

(I'm assuming you're running JavaScript in the browser, since you're dealing with HTML.)

Rather than trying to use regular expressions to parse HTML (which is generally a bad idea), you're probably better off actually building the DOM tree and then traversing it to get the content you need.

For instance, you can put that table in a disconnected div:

var div = document.createElement('div');
div.innerHTML = your_html_string;

...and then use the DOM methods (and possibly innerHTML ) and/or a library to get the content you need.

References:


If you're going to be doing a lot of work in JavaScript on the browser, I recommend using a good JavaScript library like jQuery , Prototype , YUI , Closure , or any of several others . These smooth over browser differences for you and provide a lot of utility functionality so you can focus on the problem at hand.

Why don't you use jquery library.. its simple with that.. This should do the trick

$(document).ready(function(){
    $("tr.high").remove(); 
})

Jquery .remove()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM