如何检查某个元素是否具有属性" name"从某事开始,而不是"价值"

时间:2016-08-29 13:11:34

标签: javascript jquery css html5

我将使用各种数据属性名称开头,例如"data-mo-"

假设我有这些元素:

    <span data-mo-top-fade-duration="600">Title 1</span>
    <span data-mo-bottom-fade-duration="600">Title 2</span>
    <span data-mo-right-fade-duration="600">Title 3</span>
    <span data-mo-left-fade-duration="600">Title 4</span>
      .
      .
      .

如何处理其数据属性值以某些值开头的元素的方式是可以实现的,但对于数据属性&#34; name&#34;,我没有办法如何做到这一点。

可以实现吗?

3 个答案:

答案 0 :(得分:1)

使用ES6的一种简洁方法是选择文档中的所有元素,然后选择.filter的属性名称是否以您要查找的字符串开头:

.some
const moElements = [...document.querySelectorAll('*')]
  .filter(elm => [...elm.attributes].some(
    ({ name }) => name.startsWith('data-mo-')
  ));
console.log(moElements);

或者,如果您希望避免使用散布构造中间数组,则可以<span data-mo-top-fade-duration="600">Title 1</span> <span data-mo-bottom-fade-duration="600">Title 2</span> <span data-mo-right-fade-duration="600">Title 3</span> <span data-mo-left-fade-duration="600">Title 4</span> <span>somethingElse</span>代替元素/属性集合上的数组方法:

.call
const moElements = Array.prototype.filter.call(
  document.querySelectorAll('*'),
  elm => Array.prototype.some.call(
    elm.attributes,
    ({ name }) => name.startsWith('data-mo-')
  )
);
console.log(moElements);

答案 1 :(得分:0)

如果您只想查找给定节点是否具有以特定字符串开头的属性,则可采用以下方法之一:

// node: a single HTMLELement node,
// attr: the string to test against the attribute names:
function hasAttributeStartingWith(node, attr) {

  // here we return the result, using Array.from() to turn
  // the node-map of attributes into an Array, and then
  // Array.prototype.filter() to remove any attributes that
  // do not return a true/truthy result against the supplied
  // assessment:
  return Array.from(node.attributes).filter(function(attributeNode) {
    // attributeNode: a reference to the current attribute-node
    // of the array of attribute-nodes over which we're iterating.

    // here we test to see if the nodeName (the attribute-name)
    // of the attribute-node begins with  the supplied string
    // (held in the 'attr' variable):
    return attributeNode.nodeName.indexOf(attr) === 0;

  // if the filtered array is greater than zero then
  // there are some attributes beginning with the
  // supplied string:
  }).length > 0;
}

// here we convert the nodeList returned from document.querySelectorAll()
// into an Array, using Array.from(), and iterate over those elements
// using Array.prototype.forEach():
Array.from(document.querySelectorAll('span')).forEach(function(span) {
  // 'span': a reference to the current <span> element of the
  // array of <span> elements over which we're iterating.

  // using the function within the 'if' assessment, since it
  // returns a Boolean true/false:
  if (hasAttributeStartingWith(span, 'data-mo')) {

    // using the Element.classList API to add
    // the 'hasAttributeStartingWith' class to
    // the current <span> if the function returns
    // true:
    span.classList.add('hasAttributeStartingWith');
  }

});

function hasAttributeStartingWith(node, attr) {
  return Array.from(node.attributes).filter(function(attributeNode) {
    return attributeNode.nodeName.indexOf(attr) === 0;
  }).length > 0;
}

Array.from(document.querySelectorAll('span')).forEach(function(span) {
  if (hasAttributeStartingWith(span, 'data-mo')) {
    span.classList.add('hasAttributeStartingWith');
  }
});
.hasAttributeStartingWith {
  display: inline-block;
  font-size: 1.5em;
  color: limegreen;
}
<span data-mo-top-fade-duration="600">Title 1</span>
<span data-mo-bottom-fade-duration="600">Title 2</span>
<span data-mo-right-fade-duration="600">Title 3</span>
<span data-mo-left-fade-duration="600">Title 4</span>

JS Fiddle demo

在上面所有元素都有一个以data-mo开头的属性,为了更具体地说明它,请尝试:

Array.from(document.querySelectorAll('span')).forEach(function(span) {
  if (hasAttributeStartingWith(span, 'data-mo-b')) {
    span.classList.add('hasAttributeStartingWith');
  }
});

function hasAttributeStartingWith(node, attr) {
  return Array.from(node.attributes).filter(function(attributeNode) {
    return attributeNode.nodeName.indexOf(attr) === 0;
  }).length > 0;
}

Array.from(document.querySelectorAll('span')).forEach(function(span) {
  if (hasAttributeStartingWith(span, 'data-mo-b')) {
    span.classList.add('hasAttributeStartingWith');
  }
});
.hasAttributeStartingWith {
  display: inline-block;
  font-size: 1.5em;
  color: limegreen;
}
<span data-mo-top-fade-duration="600">Title 1</span>
<span data-mo-bottom-fade-duration="600">Title 2</span>
<span data-mo-right-fade-duration="600">Title 3</span>
<span data-mo-left-fade-duration="600">Title 4</span>

JS Fiddle demo

这应该只匹配具有以字符串data-mo-b开头的属性的元素,仅设置第二个<span>元素的样式。

参考文献:

答案 2 :(得分:0)

如果我做得对,你想检查数据,所以我尝试了一些方法来完成这项工作;

function getData(index){
	if(index[0].indexOf("mo") !== -1)
    	return true
        
    return false
}

$.each($("span"), function(i,index){
	var objectKey = Object.keys($(this).data());
	if(getData(objectKey)){
    	$(this).addClass("valid")
    } else {
    	$(this).addClass("not-valid")
    }
    	
})
.valid {
    color: green
}
.not-valid {
    font-weight: bold;
    color: red;
    text-decoration: line-through
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span data-mo-top-fade-duration="600">Title 1</span>
    <span data-mo-bottom-fade-duration="600">Title 2</span>
    <span data-mo-right-fade-duration="600">Title 3</span>
    <span data-mo-left-fade-duration="600">Title 4</span>
    <span data-not-valid-one-left-fade-duration="600">Title 5</span>