简体   繁体   English

Javascript在LI标签中获取Element

[英]Javascript get Element in LI tag

I got a li that looks like: 我有一个li ,看起来像:

<li temp="true">HELLO</li>

How would I get "temp" so I can manipulate "HELLO" in JS...I know how by id or even className 我如何获得“ temp”,以便可以在JS中操纵“ HELLO” ...我知道如何通过id甚至className

In supporting browsers (that is, anything except ancient IE): 在支持的浏览器中(即,除旧版IE之外的所有内容):

var li = document.querySelector("li[temp=true]");

If support for older IE is required try this: 如果需要支持较旧的IE,请尝试以下操作:

var li = document.querySelector ? document.querySelector("li[temp=true]")
  : (function() {
      var lis = document.getElementsByTagName('li'), l = lis.length, i;
      for( i=0; i<l; i++) {
          if( lis[i].getAttribute("temp") == "true") return lis[i];
      }
      return false;
  })();

In jQuery, you can use the attribute selector: 在jQuery中,您可以使用属性选择器:

$('li[temp="true"]');

Alternatively, you can use the document.querySelectorAll() method for a native JS solution. 另外,您可以将document.querySelectorAll()方法用于本机JS解决方案。 You should be aware of the cross-browser implications of this, however: 但是,您应该了解这种跨浏览器的含义:

var ele = document.querySelectorAll('li[temp="true"]');

You can see a jsFiddle Demo of the above. 您可以看到上面的jsFiddle演示

As an aside, you should use data- attributes to store custom attributes with HTML elements, for example the correct syntax should be: 顺便说一句,您应该使用data- attribute存储带有HTML元素的自定义属性,例如,正确的语法应为:

<li data-temp="true">HELLO</li>

Iterate through all li. 遍历所有li。

var li = document.getElementsByTagName("li");
var found;
for(var i=0; i< li.length;i++){

    if(li[i].getAttribute("temp") == "true"){
       found = li[i]; break;
   }
}

console.log(found);

OR You can use native query 或者您可以使用本机查询

var found= document.querySelectorAll('li[temp="true"]');

JSFiddle JSFiddle

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM