javascript - 如何选择一个没有类和 ID 的元素,它并不总是存在?

标签 javascript html css

情况是这样的——有一个 <li>在我需要应用定位的某些条件下出现的代码中。它没有 id,没有 class。我不能使用第 nth-child,因为有时它不存在,所以下一个 <li>被选中,打破了我的设计。我已经研究这个几个月了,看来 Javascript 将是这里唯一的答案,但我什至不知道从哪里开始。

我想我可以修改源代码以提供 <li>一个 id,但这并不是我想要的那样优雅的解决方案。以这种方式修改代码将破坏插入此代码的插件的删除脚本。

如有任何帮助,我们将不胜感激。谢谢。

最佳答案

你需要做的是找出你的 li 元素的唯一点,它可以是 id、class、attribute、style、innerText 或任何东西。
例如:

  • 元素的innerText是'i am li',遍历你容器中的所有li元素,使用ele.innerText匹配它
  • 或者 li 有一个背景:红色,这是独一无二的,你可以使用 window.getComputedStyle(element).getPropertyValue("background")遍历容器中的所有 li 元素。

更新:
首先,如果你的 li 元素有独特的属性、class、id,它会更容易。

<li class="test" id="test" name="handsome"></li>
li.test {}
li#test {}
li[name="handsome"] {} // ~=, ^=, $=, *= will also work

在你的情况下,如果 a 标签的 href 属性是唯一的,你可以像下面这个简单的例子那样做。

function getTarget() {

    //find all the li elements in your container
    var $targetList = $('.container li');
    var $link;
    for( var i = 0; i < $targetList.length;i++) {
        $link = $($targetList[i]).find('a');

        //you can use any unique point to find the one
        if ($link.length && $link.attr('href') == 'xxxxxx') {
            return $targetList[i];
        }
    }
}

// the target is the li you want
target = getTarget();

此外,如果您不确定 href 值,您可以使用 string.indexOf('http://www.test.com') ,如果你的li的innerText是唯一的,换个判断就行,看你的实际情况,找到唯一点匹配即可。

关于javascript - 如何选择一个没有类和 ID 的元素,它并不总是存在?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30317214/

相关文章:

javascript - 动态访问多级对象键

javascript - 如何配置 [mode] ="' sql'"在 Angular 7 中使用 ng2-ace-editor?

javascript - 如何使用 JavaScript 停止文件上传事件

html - 不明原因的额外空间,可能是表中表周围的填充

html - overflow hidden 的CSS3缩放动画

html - 如何在div中居中导航

javascript - 如何使用@keyframes 将动画从当前位置移动到 CSS3 中的固定位置?

javascript - angularjs 谷歌地图信息窗口

html - 使用 GET 形式的代码重定向到 URL

css - 纯 CSS : calc height based on height of other divs