I want to use the javascript function getElementsByClassName to loop in some html divs that don't have the exactly class name, but it starts with the same text: "akordeon-item"
So, the html text looks like this:
<div class="akordeon-item akordeon-item-first">
<div>
<span class="userid">
[email protected]
</span>
</div>
</div>
<div class="akordeon-item akordeon-item-second">
<div>
<span class="userid">
[email protected]
</span>
</div>
</div>
<div class="akordeon-item akordeon-item-third">
<div>
<span class="userid">
[email protected]
</span>
</div>
</div>
<div class="akordeon-item akordeon-item-fourth">
<div>
<span class="userid">
[email protected]
</span>
</div>
Also, the javascript code I tried is this one:
var slides = getElementsByClassName(".akordeon-item");
for(var i = 0; i < slides.length; i++)
{
alert("element : "+slides[i]);
}
I also tried searching for this string inside the getElementsByClassName method : "akordeon-item"
How can I make this loop work? Please help...
The getElementsByClassName() method returns a collection of elements with a specified class name(s). The getElementsByClassName() method returns an HTMLCollection.
The getElementsByClassName method of Document interface returns an array-like object of all child elements which have all of the given class name(s). When called on the document object, the complete document is searched, including the root node.
The JavaScript getElementsByClassName is used to get all the elements that belong to a particular class. When the JavaScript get element by class name method is called on the document object, it searches the complete document, including the root nodes, and returns an array containing all the elements.
If you want only the first element in the DOM with that class, you can select the first element out of the array-like HTMLCollection returned. var elements = document. getElementsByClassName('className'); var requiredElement = elements[0];
There is a bunch of special selectors you can make use of:
^= is starts with
$= is ends with
= is exactly equal
!= is not equal
*= is contains
Try:
$.each($('[class^="akordeon-item"]'), function(key, value) {
console.log(key, value);
});
$.each
documentation Alternative ways to iterate over the set:
$('[class^="akordeon-item"]').each(function(key, value) {
console.log(key, value);
});
Or using a for
loop:
var slides = $('[class^="akordeon-item"]');
for (var i = 0; i < slides.length; i++) {
console.log(slides[i]);
}
$('div[class^="akordeon-item"]').each(function(index){});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With