Search code examples
javascriptjqueryarrayssplice

JQuery Remove Specific Element From Array


I'm trying to remove a certain element from my array - specifically, .top-header .header-info .header-phone a. At the same time, I'm trying to grab each other instance of .top-header .header-info a Here's my code:

var anchorArray = [];
var titleArray = [];
$('.top-header .header-info a').each(function() {
    var removeItem = $('.top-header .header-info .header-phone a')
    anchorArray.push($(this).attr('href'));
    anchorArray.splice($.inArray(removeItem,anchorArray), 1);
    titleArray.push($(this).html());
    titleArray.splice($.inArray(removeItem,titleArray), 1);
});

<div class="header-info">
  <span class="header-phone"><a href="tel:314-533-1500">314.533.1500</a>&nbsp;or&nbsp;<a href="tel:800-777-2852">1-800-777-ATLAS</a></span>
  <a href="comingsoon">Request a Consultation</a>
  <a href="quickpad">Quick Order</a>
  <a href="contactus">Contact Us</a>
</div>

Currently, this seems to be removing all instances of a links.

Thanks!


Solution

  • A better way for you to do this is to check if the parent div of the element doesnot contain the class you wish to remove. If it doesnt, then add that element.

       <!DOCTYPE html>
        <html>
        <head>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
        </head>
        <body>
    
        <div class="header-info">
          <span class="header-phone">
          <a href="tel:314-533-1500">314.533.1500</a>&nbsp;or&nbsp;
          <a href="tel:800-777-2852">1-800-777-ATLAS</a></span>
          <a href="comingsoon">Request a Consultation</a>
          <a href="quickpad">Quick Order</a>
          <a href="contactus">Contact Us</a>
        </div>
    
        <script>
        var anchorArray = [];
        var titleArray = [];
        $('.header-info a').each(function(e,s) {
            if(s.parentNode.className !=="header-phone"){
              console.log(s.parentNode.className);
              anchorArray.push($(this).attr('href'));
              console.log("anchorArray:"+anchorArray);
              titleArray.push($(this).html());
            }
        });
    
        console.log(titleArray);
        </script>
        </body>
        </html>