Toykoc
Toykoc

Reputation: 91

Search and find a DIV's content by classname

I have a div element that contains other div elements which have class names created dynamically. I need to search the container div elements' content and find the div elements by the first 3 letters of their class name.

Example:

<div>
  <div class="CTR-???????">
  </div>
  <div class="CTR-???????">
  </div>
  <div class="CTR-???????">
  </div>
</div>

I'm sure there is a way to do this with Javascript but I couldn't find that way.

Can anyone help?

Upvotes: 0

Views: 87

Answers (4)

Daan
Daan

Reputation: 2799

in jQuery you can easily do this by selecting the div's with a class starting with CTR and also check if they contain the search term like this:

$('div[class^="CTR"]:contains("Term that content has to require")').each(function() {
// do something
});

Upvotes: 0

fboes
fboes

Reputation: 2239

Assign some more classes:

<div>
  <div class="CTR CTR-???????">
  </div>
  <div class="CTR CTR-???????">
  </div>
  <div class="CTR CTR-???????">
  </div>
</div>

Now you can find these by looking for .CTR. In jQuery this would be $('.CTR') or in plain JS document.getElementsByClassName('CTR')

Upvotes: 2

James Donnelly
James Donnelly

Reputation: 128791

Native JavaScript Solution

You can use document.querySelectorAll combined with the ^= substring-matching attribute selector:

var elems = document.querySelectorAll('div[class^="CTR"]');

This will return a NodeList containing the matched elements, which looks like an array:

> [<div class="CTR-???????"></div>,
   <div class="CTR-???????"></div>,
   <div class="CTR-???????"></div>]

You can then access the individual selected elements by their index:

elems[0];
> <div class="CTR-???????"></div>

Working Demo

var elems = document.querySelectorAll('div[class^="CTR"]');

elems[0].style.color = '#f00';
elems[1].style.color = '#0f0';
elems[2].style.color = '#00f';
<div>
  <div class="CTR-???????">1</div>
  <div class="CTR-???????">2</div>
  <div class="CTR-???????">3</div>
</div>

jQuery Solution

If you're using jQuery, you can simply pass the same string I used in the above querySelectorAll example into a jQuery selector:

$('div[class^="CTA"]')

Working Demo

var elems = $('div[class^="CTR"]');

$(elems[0]).css('color', '#f00');
$(elems[1]).css('color', '#0f0');
$(elems[2]).css('color', '#00f');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>
  <div class="CTR-???????">1</div>
  <div class="CTR-???????">2</div>
  <div class="CTR-???????">3</div>
</div>

Upvotes: 1

Maurice Perry
Maurice Perry

Reputation: 32831

How about something like this:

document.querySelectorAll('[class^="CTR-"], [class*=" CTR-"]');

Upvotes: 0

Related Questions