2015-12-29 79 views
0

我有一个CSS选择器#menu li {background-color: red;}在JavaScript中获取元素ID和通用元素

我想在JavaScript中访问其属性。我必须同时访问#menuli,因为#menu本身具有不同的属性。好像getElementById(menu li), QuerySelector and getComputedStyle在这种情况下不起作用。

有没有其他办法可以达到这个目标还是我在这里错过了一些东西?

+0

你一定要使用jquery这一点。 – JonH

+2

请问您可以发布完整的代码吗? –

+0

你应该尝试'document.querySelectorAll(“#menu li”)'。这给你一个你可以使用的所有节点的列表。或者使用jQuery – chillichief

回答

0

你应该使用jQuery为此,这里的易代码示例

//html 
      <div id="menu" data-number="123" > 
      </div> 
    //jquery 
      var menu = $('#menu').attr('data-number'); 
      console.log(menu); 
      //print 123 
0

jQuery的版本

https://jsfiddle.net/pn52uvw1/

$(".button_1").click(function(){ 
    alert($("#menu").attr("data-item-id")); 
}) 
$(".button_2").click(function(){ 
    alert($("#menu li").attr("data-item-id")); 
}) 

非jQuery的版本

https://jsfiddle.net/pn52uvw1/2/

window.firstFunction = function(){ 
    var target = document.getElementById("menu"); 
    alert(target.getAttribute('data-item-id')); 
} 

window.secondFunction = function(){ 
    var target = document.getElementById("menu").children[0]; 
    alert(target.getAttribute('data-item-id')); 
} 

,但你将需要获得可能摆脱[0]指标,并使用了什么多个锂项目

0

如果你想获得该CSS规则的属性,你可以这样做:

function getStyleFromSelector(selector, styleName) { 
 
    // Get all style elements 
 
    var styles = document.styleSheets; 
 
    var styleIndex = 0, styleCount = styles.length; 
 
    var rules, ruleCount, ruleIndex; 
 
    // Iterate though styles 
 
    for (styleIndex = 0; styleIndex < styleCount; ++styleIndex) { 
 
     
 
     // Get the css rules under the style. 
 
     rules = styles[styleIndex].rules; 
 
     ruleCount = rules.length; 
 
     for (ruleIndex = 0; ruleIndex < ruleCount; ++ruleIndex) { 
 
     
 
     // Check if the selector match the one we want 
 
     if (rules[ruleIndex].selectorText === selector) { 
 
      return styleName ? 
 
       rules[ruleIndex].style.getPropertyValue(styleName) : rules[ruleIndex]; 
 
     } 
 
     } 
 
    } 
 
} 
 

 
var div = document.getElementById("results"); 
 
var result = getStyleFromSelector('#menu li'); 
 
console.log(result); 
 
div.innerHTML = 'background-color is : ' + result.style.backgroundColor; 
 
console.log(getStyleFromSelector('#menu li', 'background-color'));
#menu li {background-color: red;}
<div id="results"></div>

0

您可以通过以下

尝试没有额外的库
var len = document.querySelectorAll("#menu li").length; 
for(i = 0; i<len; i++) 
    document.querySelectorAll("#menu li")[i].style.backgroundColor="blue"; 

我也让你(一个不是很漂亮)的jsfiddle

https://jsfiddle.net/gmeewsmz/