Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I select the innermost element?

In jQuery, how would I descend as far as possible into the HTML tree?

For simplicity, I only have one path going downward.

(related but bonus: how do I find the deepest element with multiple downward paths?)

<html>  
  <table id="table0">  
    <tr>  
      <td id="cell0">  
        <div class"simple">  I want to change this information </div>  
      </td>
    </tr>  
  </table>  
</html>

I want to change the innermost HTML of the cell named cell0 but I don't necessarily know the names of all the classes inside. Is it possible to select this far without knowing these names?

Thanks much!

like image 211
sova Avatar asked Nov 15 '10 21:11

sova


People also ask

How do you access the inner elements of HTML?

Use innerHTML property of an element to get or set HTML contained within the element. The innerHTML property returns the current HTML source of the element, including any change that has been made since the page was loaded.

How do you select an element by title?

We can find and click elements by title in Selenium webdriver. An element can be identified with a title attribute with xpath or css selector. With the xpath, the expression should be //tagname[@title='value']. In css, the expression should be tagname[title='value'].

How do you select all elements in HTML?

The * selector selects all elements. The * selector can also select all elements inside another element (See "More Examples").


1 Answers

I'd do this through a single recursive function:

// Returns object containing depth and element
// like this: {depth: 2, element: [object]}
function findDeepestChild(parent) {

    var result = {depth: 0, element: parent};

    parent.children().each(
        function(idx) {
            var child = $(this);
            var childResult = findDeepestChild(child);
            if (childResult.depth + 1 > result.depth) {
                result = {
                    depth: 1 + childResult.depth, 
                    element: childResult.element};
            }
        }
    );

    return result;
}
like image 139
Jacob Avatar answered Sep 22 '22 12:09

Jacob