如何基于具有多个类的类返回一个元素

时间:2017-12-23 23:36:07

标签: javascript jquery html getelementbyid

说我有3个div

<div class="one"></div>
<div class="one two"></div>
<div class="one two three"></div>
<div class="one two"></div>
<div class="one"></div>

在我的js中,我有以下

var active = document.getElementsByClassName("one");

返回所有三个div。我只想要调用FIRST和LAST div。如何使用jquery实现这一目标?

4 个答案:

答案 0 :(得分:2)

这可以通过javascript轻松实现。只需检查classList的{​​{1}}是否仅等于您要选择的<div>即可。如果它不相等,则意味着class包含多个类。

&#13;
&#13;
classList
&#13;
function getValue()
{
  var divs = document.getElementsByClassName("one");
  
  for(var i=0; i < divs.length; i++)
  {
    if(divs[i].classList == 'one')
    {
        alert(divs[i].innerHTML);
    }
  }
}
&#13;
&#13;
&#13;

答案 1 :(得分:2)

虽然你说如何使用jquery实现这个?你可以像这样使用jquery

&#13;
&#13;
import React from 'react';
import PropTypes from 'prop-types';
import NavBar from './common/NavBar';
import Logo from './common/Logo';
import MuiThemeProvider from 'material-ui/styles/MuithemeProvider';

class App extends React.Component {
  render() {
    return (
      <MuiThemeProvider>
        <div className="container-fluid">
          <Logo />
          <NavBar />
          {this.props.children}
        </div>
      </MuiThemeProvider>
    );
  }
}

App.PropTypes = {
  children: PropTypes.object.isRequired
};

export default App;
&#13;
//$('.one:first , .one:last').css('background' , 'red');  // if you just need first one and last one

$('.one:not(.two , .three)').css('background' , 'red');  // if you need the one class but not two or three
&#13;
&#13;
&#13;

答案 2 :(得分:1)

我建议,在这种情况下:

// finding all elements whose 'class' attribute starts with
// 'one' and also ends with 'one'
document.querySelectorAll('[class^="one"][class$="one"]');

或者更简单:

// finding all elements whose class attribute-value is
// equal to 'one'
document.querySelectorAll('[class="one"]');

参考文献:

答案 3 :(得分:0)

检查jQuery equals选择器:http://api.jquery.com/attribute-equals-selector/。以下三种可能性:

jQuery("[class='My class1']")

$$("[class='My class1']")

$("[class='My class1']").