viery365
viery365

Reputation: 965

How to target elements that have the same class without specifying the name of the class

I am new to jQuery so please forgive me if the question is too basic.

I know how to target two or more elements with the same class if I know the name of the class. My problem is that the name of many classes in the website I am building are created dynamically. So, I don't have much control about the specific name of the classes.

What I am trying to do is to target 2 elements when they have the same class even if I don't know the name of the class .

Ex:

<a href="#" class="title25">Some text</a>
<figcaption class="title25">Some text</figcaption>

So, when these elements have the same class (whatever it is) do something, when they don't do something else but without providing something like .title25 in my jQuery.

Upvotes: 4

Views: 681

Answers (4)

Lex Lustor
Lex Lustor

Reputation: 1625

Start by getting all a elements and for each of them, you look for figcaption with the same class

$("a").each(function() {
    // Here, 'this' is the current a element in the loop
    var currentClass = $(this).attr("class");
    // Search for a figcaption element with the same class
    var correspondingFigcaption = $('figcaption.' + currentClass);
    if(correspondingFigcaption.length > 0){
         // Here, 'this' is your a element
         // and correspondingFigcaption.get(0) is the first corresponding figcaption
    }
});

Of course, you can check that you obtain only one figcaption corresponding element but I let the full use to you.

Upvotes: 1

Himel Nag Rana
Himel Nag Rana

Reputation: 744

This can be achieved many ways. I would do that like -- asking for all types of class used in the page. Then accessing the elements using them in loops would have been easy. And that's subjective to what really you want to do with them.

My code goes:

<a href="#" class="title25">Some text1</a>
<figcaption class="title25">Some text2</figcaption>
<div class="title30">Some text3</div>
<span class="title30">Some text4</span>
<p class="title50">Some text5</p>
<ul class="title50">
  <li>Some text6</li>
</ul>

Here the example is shown with jQuery. You can also use raw javascript or any other frameworks.

var classes = [];
$('[class]').each(function(){
     $($(this).attr('class').split(' ')).each(function() { 
        if (this.length>0 && $.inArray(this.valueOf(), classes) === -1) {
            classes.push(this.valueOf());
        }    
    });
});

console.log(classes);

classes.forEach(function(i){
  $('.'+i+':first').attr("style", "color: red;");
  $('.'+i+':last').attr("style", "color: green;");

  $('DIV.'+i).attr("style", "font-size: 24px;");
  $('p.'+i).attr("style", "font-weight: 800;");
  $('span.'+i).attr("style", "text-decoration: underline;");
});

JSFiddle Link: https://jsfiddle.net/27g7aayt/1/

Upvotes: 1

zer00ne
zer00ne

Reputation: 44086

Plain JavaScript:

  • gather 2 NodeLists of anchors and captions with querySelectorAll()
  • convert each NodeList to arrays with Array.prototype.slice.call()
  • merge both arrays with concat()
  • iterate through the merged array and on each iteration find the element's className
  • then unshift (or push) the className into a new array
  • pass the new array through the function findTwin()
  • findTwin()
    • loops through the length of the array and stores each element in an object to compare with the next element.
    • matches and singles are separated into an array of doubles and an array of uniques.
    • the array with doubles is returned and with a modification the array of singles could be used if desired.
    • The Snippet has a series of anchors and captions. There are 2 doubles: title25 and title00.

Snippet

var ancs = document.querySelectorAll('a');
var caps = document.querySelectorAll('figcaption');

var aArray = Array.prototype.slice.call(ancs);
var cArray = Array.prototype.slice.call(caps);

var mergedArray = aArray.concat(cArray);
var total = mergedArray.length;

var classArray =[];

for (var i = 0; i < total; i++) {
  var aClass = mergedArray[i].className;
  classArray.unshift(aClass);
}


var twins = findTwin(classArray);

console.log('matched: ' + twins);

function findTwin(arr) {
  var singleArray = [];
  var doubleArray = [];
  var total = arr.length;
  var sorted = {};

  while (total--) {
    var item = arr[total];

    if (!sorted[item]) {
      singleArray.unshift(item);
      sorted[item] = true;
    } else {
      doubleArray.unshift(item);
      sorted[item] = true;
    }
  }
  return doubleArray;
}
<script src="http://gh-canon.github.io/stack-snippet-console/console.min.js"></script>
<a href="#" class="title00">Some text</a>
<figcaption class="title05">Some text</figcaption>
<a href="#" class="title55">Some text</a>
<figcaption class="title27">Some text</figcaption>
<a href="#" class="title28">Some text</a>
<figcaption class="title85">Some text</figcaption>
<a href="#" class="title25">Some text</a>
<figcaption class="title25">Some text</figcaption>
<a href="#" class="title35">Some text</a>
<figcaption class="title00">Some text</figcaption>
<a href="#" class="title45">Some text</a>
<figcaption class="title26">Some text</figcaption>

Upvotes: 1

Axel Couturier
Axel Couturier

Reputation: 168

Something like this:

$("a").each(function(index, element) {
    var class = $(element).attr("class");
    if(class.length > 2) {
       // do something
    }
});

Not tested..

Upvotes: 1

Related Questions