【问题标题】:Selecting all elements up until reaching a specific one选择所有元素直到达到特定元素
【发布时间】:2013-04-21 08:10:39
【问题描述】:

有一个容器 div,里面有其他 div,这些子 div 包含文本和一些链接。我正在尝试选择此容器 div except 内的所有锚标记,用于那些在 具有特定类的子 div 之后出现的标记。 p>

<div id="the_container">

 <div>
  some text <a href="...">link</a>
 </div>
 <div>
  some text <a href="...">link</a>
 </div>
 ... more regular divs below...

 <div class="NOT_a_regular_child">
  this is not text
 </div>

 <div>
  some text <a href="...">link</a>
 </div>
 ... more divs come below...

</div>

所以,从上面的 HTML 中,我想只选择 div 之前的链接,哪个类是“NOT_a_regular_child”。

我用谷歌搜索了它,但似乎没有用于在另一个之前获取元素的选择器(?)

我相信我可以选择所有子 div,然后循环遍历它们并将它们的链接转储到一个数组,直到我到达那个特定的,但没有办法只使用 css 选择器吗?

我无法更改 HTML 的结构,因为我只是在编写一个 google chrome 扩展程序以在现有网站上工作。

【问题讨论】:

  • jQuery nextUntil: dir: function(elem, dir, until ) { var match = [], cur = elem[ dir ]; while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) { if ( cur.nodeType === 1 ) {matched.push(cur); } cur = cur[dir]; } 返回匹配; },

标签: javascript html css dom css-selectors


【解决方案1】:

纯 CSS

设置一个纯 css 方式来定位那些使用通用兄弟选择器 ~ 的人并不复杂。

See this fiddle 了解以下代码性能。

.the_container a {
    color: blue; 
    /* base link color and styling for container 
       this will be applied to all links above the class
    */
}

/* second selector is optional only if you need to 
handle links in that specially classed container */

.the_container > div.NOT_a_regular_child ~ div a,
.the_container > div.NOT_a_regular_child a /* <-- optional */
{
    color: red;
    /* base link color and styling for container 
       this will be applied to all links above the class
    */
}

【讨论】:

  • 问题似乎是关于使用选择器将给定元素与 JavaScript 匹配,正如我在删除的答案中所说的那样,这是无法完成的。我不确定你的答案是否适合手头的问题,但是当使用 CSS 时,这里的覆盖技术肯定会非常方便。
  • 好吧,这很酷!我不知道那个选择器。谢谢
  • @BoltClock 是的,我选择 js 中的链接是为了给它们应用一些样式,但我想我可以在页面上附加另一个样式元素并这样做对吗?
  • 如果只需要样式,这绝对是要走的路。我掩盖了部分问题,不知何故认为需要一个hrefs数组。 ...我也可以发誓我在问题中看到了 jQuery。所以无论如何我的答案是错误的。
  • @Delta:在这种情况下,是的,你应该可以。我最初的印象是您试图匹配 DOM 脚本的元素,而不是应用样式。
【解决方案2】:

试试这个:

function get_p_class(){
var childDivs = document.getElementById('the_container').getElementsByTagName('div');

for(var childDiv = 0;  childDiv < childDivs.length; childDiv++){
    if(childDivs[childDiv].className=="NOT_a_regular_child"){
        //code...
        childDivs[childDiv].className="this_new_class";
        //some other change 
        //or 
        //change the if statement to match what every you would like to do.
    }
 }
}

window.onload = function() {
        get_p_class();
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-18
    • 1970-01-01
    • 2012-02-05
    • 2012-06-07
    • 2016-12-12
    • 1970-01-01
    相关资源
    最近更新 更多