简体   繁体   中英

Remove specific html code using javascript/jquery

<div id="mn">

    <p article="game" a_type="advertisement" cid="#P6_001"></p> 
    <p article="let" cid="#P6_005"></p> 
    <dc_title article="start" check_zone="true" a_type="masthead" cid="#P6_006"></dc_title> 
    <p article="end" cid="#P6_047"></p> 
    <p article="start" a_type="advertisement" cid="#P6_001"></p> 
    <p article="end" cid="#P6_005"></p> 
    <dc_title article="sd" check_zone="true" a_type="masthead" cid="#P6_006"></dc_title> 
    <p article="end" cid="#P6_047"></p> 
</div>

i have a code like that. i wanna remove tags that have article="start" attribute and next tag has article="end"

<dc_title article="start" check_zone="true" a_type="masthead" cid="#P6_006"></dc_title> 
<p article="end" cid="#P6_047"></p> 

so after fix above code i wanna display it like this:

<p article="game" a_type="advertisement" cid="#P6_001"></p> 
<p article="let" cid="#P6_005"></p> 
<dc_title article="sd" check_zone="true" a_type="masthead" cid="#P6_006"></dc_title> 
<p article="end" cid="#P6_047"></p>

If you are willing to use jQuery (or if it's possible in your project), you can do the following:

elements = $('[article="start"] + [article="end"]');
elements.prev().detach();
elements.detach();

The first line selects all elements that have article=end directly preceded by an element with article=start . The second line deletes the article=start elements and the third line deletes the article=end elements.

You can achieve this using jquery jsfiddle work out .

     var selector1=$( 'p[article="start"]');
     var selector2=$( 'dc_title[article="start"]');
     selector2.next('p[article="end"]').remove();
     selector1.next('p[article="end"]').remove();
     selector1.remove();
     selector2.remove();

Get reference to the nodes with var dv = getElementsByAttribute('article','start');

for(var i=0;i<dv.length;i++){
 if(dv[i].nextSibling.getAttribute('article')=="end")
    var ref = dv[i];
    ref.parentNode.removeChild(ref.nextSibling);
    dv[i].parentNode.removeChild(dv[i]); 

 }



var getElementsByAttribute = function (attr, value) {
  var match = [];

  /* Get the droids we're looking for*/
  var elements = document.getElementsByTagName("*");

  /* Loop through all elements */
  for (var ii = 0, ln = elements.length; ii < ln; ii++) {

    if (elements[ii].hasAttribute(attr)) {

      /* If a value was passed, make sure it matches the element's */
      if (value) {

        if (elements[ii].getAttribute(attr) === value) {
          match.push(elements[ii]);
        }
      } else {
        /* Else, simply push it */
        match.push(elements[ii]);
      }
    }
  }
  return match;
};

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