How to check if some element has attribute "name" starts with something, not "value"

jquery check if element has attribute value
check if element has attribute jquery
hasattribute
javascript check if element has attribute value
jquery has attribute selector
javascript has attribute with value
javascript check if class has attribute
check if element has id javascript

I'm going to use various data attributes names start with for example "data-mo-".

Assume I have these elements:

<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>

I know how to handle elements whose data attribute values start with some value, but how can it be done for the data attribute names?

If all you wish to do is find whether a given node has an attribute beginning with a specific string, then one approach is the following:

// 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>

Element.hasAttribute(), On this Page. The Element. hasAttribute() method returns a Boolean value indicating whether the specified element has the specified attribute or not. When an attribute does not exist on an element some browsers return it as undefined and some as boolean false, therefore, we need to check for both values.; In ECMAScript 5 below, undefined can actually be overwritten, but this should not matter much if you're in control of the coding.

A concise approach using ES6 is to select all elements in the document, then .filter by whether .some of the attribute names start with the string you're looking for:

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>

How to Check If an Element Has Attribute Using jQuery and , !== false) { // do something } When an attribute does not exist on an element some browsers return it as undefined and some as boolean false� Definition and Usage. The hasAttribute() method returns true if the specified attribute exists, otherwise it returns false. Tip: Use setAttribute() to add a new attribute or change the value of an existing attribute on an element.

If I get it right you want to check for data-mo so I have tried something to make this work;

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>

HTML DOM hasAttribute() Method, Example. Find out if a <button> element has an onclick attribute: var x = document. String, Required. The name of the attribute you want to check if exists� A StackOverflow thread has some pretty good solutions. Get the attribute, check the value var attr = $(this).attr('name'); // For some browsers, `attr` is undefined; for others, `attr` is false.

jQuery hasAttr checking to see if there is an attribute on an element , var attr = $(this).attr('name'); // For some browsers, `attr` is undefined; for others, // `attr` is false. Check for both. if (typeof attr !== typeof undefined && attr� In contrast, jQuery.data(element) always returns a data object to the caller, creating one if no data object previously existed. This will only check for the existence of any data objects (or events) on your element, it won't be able to confirm if it specifically has a "timer" object.

A jQuery hasAttr() Equivalent, A StackOverflow thread has some pretty good. Check for both. if (typeof attr !== typeof undefined && attr !== false) { // Element has this� I would like to get all the <script> tags in a document and then process each one based on the presence (or absence) of certain attributes.. E.g., for each <script> tag, if the attribute for is present do something; else if the attribute bar is present do something else.

How to check existence of an attribute with JavaScript/jQuery , attr() method which returns value of the attribute for an element if it is present and returns undefined if attribute doesn't exist. JS; HTML. JS. The :has() CSS pseudo-class represents an element if any of the selectors passed as parameters (relative to the :scope of the given element) match at least one element. The :has() pseudo-class takes a relative selector list as an argument.

Comments
  • Great, Where is your code?
  • Please post the code you have tried so far.
  • You didn't get the idea?! @SudharsanS .. Wait.
  • Possible duplicate of jQuery - How to select value by attribute name starts with
  • Question updated..
  • array.some(f) should be more efficient than array.filter(f).length > 0. Also, string.startsWith("something") instead of string.indexOf("something") === 0. (Maybe even [].some.call(node.attributes, f) if that works; not tested.)
  • Many thanks indeed, it really is a beautiful piece of code :)