2013-09-04 32 views
6

Làm cách nào tôi có thể chọn với javascript hoặc jQuery kế hoạch mỗi phần tử có thuộc tính bắt đầu bằng "data-"?Chọn các yếu tố bắt đầu bằng "data-"

Tôi đã thử

$("[data-*"]) 

nhưng nó không hoạt động.

+0

sau khi chọn những gì u phải làm .Những gì bạn đã cố gắng cho đến nay.điều gì là yêu cầu của bạn. – Sasidharan

+0

bạn cần sử dụng công cụ chọn thuộc tính theo cách này, http: //api.jquery.com/attribute-equals-selector/ – dreamweiver

+0

Vui lòng hiển thị cho chúng tôi html của bạn – Vladimir

Trả lời

5

Dưới đây là một hàm phi JQuery rằng sẽ làm những gì bạn cần:

function getAllDataElements() { 
    //get all DOM elements 
    var elements = document.getElementsByTagName("*"); 
    //array to store matches 
    var matches = []; 
    //loop each element 
    for (var i = 0; i < elements.length; i++) { 
     var element = elements[i]; 
     //get all attributes for the element and loop them 
     var attributes = element.attributes; 
     for (var j = 0; j < attributes.length; j++) { 
      //get the name of the attribute 
      var attr = attributes.item(j).nodeName; 
      //check if attibute name starts with "data-" 
      if (attr.indexOf("data-") == 0) { 
       matches.push(element); //add it to matches 
      } 
     } 
    } 
    return matches; //return results 
} 

Mà có thể được sử dụng như sau:

var results = getAllDataElements(); 

results.forEach(function (i) { 
    i.style.color = "#FF0000"; 
}); 

Here is a working example

Các vấn đề liên quan