skip to Main Content

I have recently been trying to understand how to select elements and manipulate them using the html tree generator and JavaScript. How do I select the second last element of the last element child and also how do I select the links in order to manipulate them.

To select the second last element in the last element child I tried using :

document.firstElementChild.lastElementChild.lastElementChild.lastElementChild

…..but I still get a null hence cant change the element value.

2

Answers


  1. Selecting the Second Last Element of the Last Element Child:

    const lastElementChild = document.body.lastElementChild;
    
    const children = lastElementChild.children;
    const secondLastElement = children[children.length - 2];
    

    Selecting and Manipulating Links

    const allLinks = document.querySelectorAll('a');
    
    allLinks.forEach(link => {
        link.textContent = ""; 
        link.href = ""; 
    });
    
    Login or Signup to reply.
  2. You need to select the second last element of the last element child. That needs to be checked conditionally.

    Refer the code below for more reference:

    var lastElementChild = document.firstElementChild.lastElementChild;
    if (lastElementChild && lastElementChild.children.length >= 2) { // Check last element available and it has children 
        var secondLastElement = lastElementChild.children[lastElementChild.children.length - 2]; // if above is truthy then select the second last child of lastElementChild
        secondLastElement.textContent = "New Value"; // Now change the second element
    } else {
        console.log("Unable to find the second last element.");
    }
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search