Select an item by tag / class name length

I would like to select an element using javascript / jquery in Tampermonkey.

The class name and element tag change each time the page loads. So I have to use some form of regular expressions, but I can’t figure out how to do this.

Here's what the HTML looks like:

<ivodo class="ivodo" ... </ivodo>
<ivodo class="ivodo" ... </ivodo>
<ivodo class="ivodo" ... </ivodo>
  • The tag always matches the class name.
  • This is always a 4 letter random "code"

I assume it will be something like this: $ ('[/ ^ [AZ] {4,5} /}')

Can someone help me get the correct regular expression?

+4
source share
4 answers

regexp . - , . , .

: https://codepen.io/anon/pen/RZXdrL?editors=1010

HTML:

<div class="container">
  <abc class="abc">abc</abc>
  <abdef class="abdef">abdef</abdef>
  <hdusf class="hdusf">hdusf</hdusf>
  <ueff class="ueff">ueff</ueff>
  <asdas class="asdas">asdas</asdas>
  <asfg class="asfg">asfg</asfg>
  <aasdasdbc class="aasdasdbc">aasdasdbc</aasdasdbc>
</div>

js ( jQuery):

const $elements = $('.container *').filter((index, element) => {
  return (element.className.length === 5);
});

$elements.css('color', 'red');
+2

- , :

$('#parent > *').each(function() {
  // your logic here...
})
+2

, , , , , , , :

var $elements  = $('*').filter(function() {
    return this.className.length === 5 && this.className.toUpperCase() === this.tagName.toUpperCase();
});

DEMO

, . , '*' :

var $elements  = $('someSelector *').filter(function() {
    return this.className.length === 5 && this.className.toUpperCase() === this.tagName.toUpperCase();
});
+1

vanilla JS DEMO

demo dev

<body>
  <things class="things">things</things>
  <div class="stuff">this is not the DOM element you're looking for</div>
</body>

JS

// Grab the body children
var bodyChildren = document.getElementsByTagName("body")[0].children;

// Convert children to an array and filter out everything but the targets
var targets = [].filter.call(bodyChildren, function(el) {
  var tagName = el.tagName.toLowerCase();
  var classlistVal = el.classList.value.toLowerCase();
  if (tagName === classlistVal) { return el; }
});

targets.forEach(function(el) {
// Do stuff
  console.log(el)
})
+1

Source: https://habr.com/ru/post/1685401/


All Articles