简体   繁体   中英

Javascript get Element in LI tag

I got a li that looks like:

<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

In supporting browsers (that is, anything except ancient IE):

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

If support for older IE is required try this:

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:

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

Alternatively, you can use the document.querySelectorAll() method for a native JS solution. 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.

As an aside, you should use data- attributes to store custom attributes with HTML elements, for example the correct syntax should be:

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

Iterate through all 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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