Deleting a table row using Javascript through content identification

I'm working with the following code:

<table>
    <tbody>
        <tr>
            <td align="left">X</td>
            <td>X1</td>     
        </tr>
        <tr>        
            <td width="150" align="left">Y</td>
            <td>Y1</td>
        </tr>
        <tr>    
            <td align="left">Status: </td>
            <td colspan="4">
                <select name="status" size="1">
                    <option selected="selected" value="2">one</option>
                    <option value="1">two</option>
                </select>                   
            </td>
        </tr>
        <tr>        
            <td width="150" align="left">Z</td>
            <td>Z1</td>
        </tr>   
    </tbody>
</table>

My goal is to delete this specific line using Javascript:

<tr>    
    <td align="left">Status: </td>
    <td colspan="4">
        <select name="status" size="1">
            <option selected="selected" value="2">one</option>
            <option value="1">two</option>
        </select>                   
    </td>
</tr>

The challenge is that there are no IDs or classes for identification. Is it possible to remove the row by searching for "Status: " or name="status" using JavaScript specifically for Firefox (intending to use it with Greasemonkey)?

Unfortunately, jQuery cannot be used and the code cannot be edited to add any IDs.

Warm regards, Bernte

Answer №1

If your website doesn't need to support IE7, you have the option to do the following:

var elements = document.querySelectorAll('td[align="left"]');
for (var i=0; i<elements.length; i++) {
    var text = elements[i].textContent || elements[i].innerText;
    if (text.trim()=='Status:') {
       elements[i].parentNode.parentNode.removeChild(elements[i].parentNode);   
    }
}

See it in action here

If you want compatibility with IE7, you may need to iterate through all rows and cells, although this approach might be less straightforward.

Keep in mind that I used trim, which is not supported in IE8. To make it work on this browser if necessary, you can use this common workaround (from MDN):

if(!String.prototype.trim) {
  String.prototype.trim = function () {
    return this.replace(/^\s+|\s+$/g,'');
  };
}

Answer №2

function deleteRowByValue(table, value) {
    var cells = table.getElementsByTagName("TD");
    for(var i = 0; i < cells.length; i++) {

        // Make sure the cell has a child node to prevent errors
        if(!cells[i].firstChild) {
            continue;
        }

        if(cells[i].firstChild.nodeValue == value) {
            var row = cells[i].parentNode;
            row.parentNode.removeChild(row);
            break;
        }
    }
}

To start off, find your table by using getElementsByTagName since there is no ID available (assuming it's the first table in the document).

var myTable = document.getElementsByTagName("table")[0];

Next, call the function with the required parameters:

deleteRowByValue(myTable,"Status: ");

Answer №3

let findStatus = document.evaluate("//td[starts-with(.,'Status:')]", document.body, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
let statusElement = findStatus.singleNodeValue.parentNode;
while (statusElement.firstChild)
  statusElement.removeChild(statusElement.firstChild);

View the code on Jsbin at http://jsbin.com/urehuw/1/edit

Answer №4

Do you want your code to be compatible with older versions of Internet Explorer?

function closestElement(el, tag) {
    if (!el || !tag) {
        return false;
    }
    else {
        return el.parentNode.tagName.toLowerCase() == tag ? el.parentNode : closestElement(el.parentNode, tag);
    }
}

// Retrieve all 'select' elements
var selectElements = document.getElementsByTagName('select');

// Iterate through each 'select' element found
for (var i=0, length = selectElements.length; i<length; i++) {
    // Check if the 'select' element has the name attribute set to 'status'
    if (selectElements[i].name == 'status') {
        // Use the closestElement() function to find the nearest ancestor 'tr' element
        var tableRow = closestElement(selectElements[i], 'tr');
        // Remove the 'tr' child element from its parent
        tableRow.parentNode.removeChild(tableRow);
    }
}

Check out the JS Fiddle demo here.

Answer №5

try this method

    let selectTag = document.getElementsByTagName("tr")[3]; // selecting the third tr tag
         document.removeChild(selectTag);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using the jQuery dialog to load a URL with a datetime picker integrated into

I recently created two pages. One page contains a link that opens a dialog and loads another page inside that dialog. However, when I click on the calendar on the loaded page, I receive the error message: "Cannot read property 'inline' of undefin ...

Looking to tally a value every time a checkbox is checked within the onchange function

Hey everyone, I'm working on adding a priority number when a checkbox is checked using the onchange function. When a checkbox is checked, it should be marked as 1. I have a list of checkboxes within a div, and when one checkbox is checked, it should b ...

In JavaScript, if a string matches a property in an array, then the array can be reordered with the

Currently, I am utilizing an Angular 5 pipe to manipulate an array before displaying it using ngFor. The array consists of all active users, and my goal is to ensure that the user who is currently logged in always appears at the beginning of the array so ...

Unable to define checkbox with dynamic id in Protractor

Seeking assistance in defining and selecting a specific checkbox to complete the account creation process. The challenge lies in the fact that part of the input id is dynamic and changes with each execution. Hence, the current method is ineffective: var n ...

Unexpected behavior encountered with JQueryUI modal functionality

Today marks my first experience with JqueryUI. I am attempting to display a conditional modal to notify the user. Within my ajax call, I have this code snippet: .done(function (result) { $('#reportData').append(result); ...

Pass SASS/SCSS variables to Javascript without the need to export them to CSS files

Context Let's take a look at the _variables.scss file below: /* Setting up color variables */ $white: #fff; $black: #000; $grey: #ccc; // and so on... // Export the color palette for Javascript accessibility :export { white: $white; ...

Develop an Engaging JavaScript Quiz with Elements That are Generated Dynamically

** Need help setting answer values for checkboxes Currently, I have a code that displays (2) questions with (4) possible answers each. Next to each answer is a checkbox with a default value of false. However, I want to link the value of each checkbox to ...

Utilizing ReactJS for Web Development with Enhanced Data Insights from Google

Utilizing Google Analytics and various tools, I've encountered an issue with the development of ReactJS. My goal was to collect analytics data from my website by using react-helmet to dynamically change the title and the HTML lang parameter based on t ...

Material UI: Easily adjusting font size within Lists

When developing forms with react js and material UI, I encountered an issue with changing the font size within lists to achieve a more compact layout. The code fontSize={10} didn't seem to have any effect regardless of where I added it. Is there a wa ...

Firing a function in Angular2 whenever an observable property undergoes a change

Utilizing a workingData service that stores crucial data across my application, it provides an observable to the Mock workingData object. @Injectable() export class WorkingDataService { getWorkingData(): Observable<WorkingData> { return Observ ...

Tips for incorporating a multimedia HTML/JavaScript application within C++ programming

I possess the source code for a JavaScript/HTML5 application that operates on the client-side and manages the transmission/reception of audio and video data streams to/from a server. My objective is to develop a C++ application that fully integrates the c ...

Choose documents based on a specified range of _id values in mongoose

I am in the process of developing a new application that enables users to generate subtables from main tables, giving them the ability to specify a specific range of rows to include in the subtable. Introducing my Subtable model: // Required Imports con ...

Avoid abrupt image flickering when the source is being changed

I'm encountering an issue with image flickering when using large images. Within my body, I have a set of 5 images: <img id="img1" src="img1.png" width="250"> <img id="img2" src="img2.png" width="250"> <img id="img3" src="img3.png" widt ...

Am I properly preloading images with this method?

Is the following method appropriate for preloading images? I have a table that changes its background when a 'select option' is changed. On my page's body, I include: <body onload="preload();"> Within the Form on the same page, I ha ...

Is there a way for me to identify what deletes CSS classes from an element during the first page load?

On a page where an element (specifically, a TextBox) initially has two CSS classes assigned when it loads, something strange is happening. After the page renders and JavaScript runs, the class attribute of the input element mysteriously becomes empty. I c ...

Is there a way to determine the dimensions of an HTML element? (taking into account added elements)

It seems that the current situation is not feasible at this time. I am working on an animation that requires an element to move from an absolute position to an inline one. The challenge is that I cannot predict how the container or the element itself will ...

Why is it important to understand the meaning of variable = [...variable] in Javascript ES6?

I need clarification on the following variable arg assignment arg = [...arg]; Can you explain what this code snippet does? ...

What are your top choices for customizable dropdowns/menus with enhanced features?

I came across a cool feature on the YUI website, check it out here: http://developer.yahoo.com/yui/examples/button/btn_example07.html Does anyone have recommendations for a library/plugin to enhance native select element dropdowns in response to a client& ...

Changing the content of a <div> element using the information retrieved from the previous page

When the user clicks the "Edit" button, I am redirecting them from another page using the following code snippet. $('#editListButton').click(function(){ window.location.href = "http://localhost/yyy.php"; //redirect // Modifications th ...

Ensure that the test files include the export default module

I'm currently facing an issue when trying to import a module in my test files, specifically when it's exported as a default module. My code looks like this: server.ts import { MyClass } from './myClass'; /* Other code here */ const ...