开发者

Using JQuery to traverse DOM structure, finding a specific <table> element located after HTML 'comment'

I currently have a website source code (no control over the source) which contains certain content that needs to be manipulated. This would be simple on the surface, however there is no unique ID attribute on the tag in question that can uniquely identify it, and therefore allow for further traversal.

Here is a snippet of the source code, surrounding the tag in question.

   ...
    <td width="100%"> 

     <!--This table snaps the content columns(one or two)--> 

     <table border="0" width="100%"> 
   ...

Essentially, the HTML comment stuck out as an easy way to gain access to that element. Using the JQuery comment add-on from this question, and some help from snowlord comment below, I have been able to identify the comment and retrieve the following output using the 'dump' extension.

$('td').comments().filter(":contains('This table snaps the content columns(one or two)')").dump();

returns;

j开发者_JS百科Query Object {   
    0 = DOMElement [ 
        nodeName: DIV
        nodeValue: null
        innerHTML: [ 
            0 = String: This table snaps the content columns(one or two)
        ]
    ] 
}

However I am not sure how to traverse to the sibling element in the DOM.

This should be simple, but I haven't had much selector experience with JQuery. Any suggestions are appreciated.


I am thinking you could use the siblings method:

$('td').comments().siblings('table').yourcode...

From the docs:

Given a jQuery object that represents a set of DOM elements, the .siblings() method allows us to search through the siblings of these elements in the DOM tree and construct a new jQuery object from the matching elements.

The method optionally accepts a selector expression of the same type that we can pass to the $() function. If the selector is supplied, the elements will be filtered by testing whether they match it.


If you have any control over this code at all, put an id on the table.

If you have to do something nasty, perhaps you could use

var tables = $("table");

To get all tables and then ascertain the table in question by index...

$(tables[5]).css("color", "aqua");

This breaks as soon as a table is added or removed, but if you cannot add an id to the table it seems like a potential alternative.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜