How can I count the number of elements with same class? - javascript

I have a main div in my page with a specific id. Now some input elements of the same class are present in this div. So how can I count the number of these elements of same class in this div using jQuery?

With jQuery you can use
$('#main-div .specific-class').length
otherwise in VanillaJS (from IE8 included) you may use
document.querySelectorAll('#main-div .specific-class').length;

document.getElementsByClassName("classstringhere").length
The document.getElementsByClassName("classstringhere") method returns an array of all the elements with that class name, so .length gives you the amount of them.

You can get to the parent node and then query all the nodes with the class that is being searched. then we get the size
var parent = document.getElementById("parentId");
var nodesSameClass = parent.getElementsByClassName("test");
console.log(nodesSameClass.length);
<div id="parentId">
<p class="prueba">hello word1</p>
<p class="test">hello word2</p>
<p class="test">hello word3</p>
<p class="test">hello word4</p>
</div>

$('#maindivid').find('input .inputclass').length

I'd like to write explicitly two methods which allow accomplishing this in pure JavaScript:
document.getElementsByClassName('realClasssName').length
Note 1: Argument of this method needs a string with the real class name, without the dot at the begin of this string.
document.querySelectorAll('.realClasssName').length
Note 2: Argument of this method needs a string with the real class name but with the dot at the begin of this string.
Note 3: This method works also with any other CSS selectors, not only with class selector. So it's more universal.
I also write one method, but using two name conventions to solve this problem using jQuery:
jQuery('.realClasssName').length
or
$('.realClasssName').length
Note 4: Here we also have to remember about the dot, before the class name, and we can also use other CSS selectors.

Simplest example:
document.getElementById("demo").innerHTML = "count: " + document.querySelectorAll('.test').length;
<html>
<body>
<p id="demo"></p>
<ul>
<li class="test">Coffee</li>
<li class="test">Milk</li>
<li class="test">Soda</li>
</ul>
</body>
</html>

Related

Remove randomly generated class and id in with Javascript?

I want to remove the class and id in the website using only Javascript. But that site's class and id contains random numbers and random characters, which looks like this:
<body class="class-abc ahwk-1726-rand_banner-lauwj-5210 other-class">
<div id="fire-id 3762-kahm-rand-banner_9728-jege other-id">
...
The common point of these classes and ids are in the form (some digits or characters)(- or _)banner(- or _)(some numbers or characters).
With CSS, I can easily select them using the CSS Selector: [class*="banner" i] and [id*="banner" i].
However, with the remove() in javascript it does not support CSS Selector.
So, how do I remove classes and ids of this form using Javascript?
Your answer will be highly appreciated!
As you are happy with the CSS selector, just iterate over the matches and delete them. But please note that it is not valid HTML when you have id attributes with spaces in them. An id attribute specifies one identifier, not a space-separated list of them.
So assuming that your HTML would be valid, you can do as follows:
for (let elem of document.querySelectorAll('[id*="banner" i]')) {
elem.removeAttribute("id");
}
for (let elem of document.querySelectorAll('[class*="banner" i]')) {
elem.classList.remove(...elem.className.match(/\S+banner\S+/gi));
}
console.log(document.querySelector("div").outerHTML);
<div class="class-abc ahwk-1726-rand_banner-lauwj-5210 other-class">
<div id="fire-id">
</div>
<div id="3762-kahm-rand-banner_9728-jege">
</div>
<div id="other-id">
</div>
</div>
So for id attributes we may assume that the id attribute can be removed. For class attributes we can search the value for the match(es) using a regular expression, and then pass the matching list to the classList.remove method.
Dealing with invalid HTML
If you really want to change the value of an invalid id property with spaces, then proceed as follows:
for (let elem of document.querySelectorAll('[id*="banner" i]')) {
elem.setAttribute("id", elem.getAttribute("id").replace(/\S+banner\S+/gi, "").replace(" ", " "));
}
for (let elem of document.querySelectorAll('[class*="banner" i]')) {
elem.classList.remove(...elem.className.match(/\S+banner\S+/gi));
}
console.log(document.querySelector("div").outerHTML);
<div class="class-abc ahwk-1726-rand_banner-lauwj-5210 other-class">
<!-- invalid HTML follows... --->
<div id="fire-id 3762-kahm-rand-banner_9728-jege other-id">
</div>
</div>
If you want to remove class or id from specific elements then find elements by tag name and remove class / id attrs like: element.removeAttribute('class') OR element.removeAttribute('id')

Check if document contains a class similar to the specified string in Javascript

I am trying to find all elements that contain 'ad'.
Such as:
<iframe class="container" /> <!-- False -->
<a class="adp" /> <!-- True -->
<a class="adleft" /> <!-- True -->
<a class="some-other-class" /> <!-- False -->
Could I use a forEach?
I appreciate any help from everyone.
You can simply achieve this with the combination of querySelectorAll and attribute selector by using the [attr*=value] syntax.
The above attribute selector syntax will work like:
Represents elements with an attribute name of attr whose value contains at least one occurrence of value within the string.
The outcome combination of above solution will be something like this:
document.querySelectorAll("[class*='ad']");
Which give you all the elements whose contain ad within their class names. Then you can simply use a simple loop or array helper like Array#forEach to use the outcome. Note that the previous outcome will produce an HTMLCollection which needs to convert into an array before using array helpers, otherwise you can use the traditional for loop over it.
Here how the final code should look like:
const ads = document.querySelectorAll("[class*='ad']");
Array.from(ads).forEach(el => {
console.log(el);
})
<iframe class="container"></iframe>
<a class="adp"></a>
<a class="adleft"></a>
<a class="some-other-class"></a>
NOTE: You always need to properly open and close HTML tags especially iframe. Since it is not assumed as a self-closing tag it will lead to invalid HTML markup.
You can use an attribute selector to get every elements containing ad. You can read more about it here : doc
document.querySelectorAll('*[class*="ad"]');

jquery complex selector by element and class starting with

I'm using jQuery in my website.
I want to select all the <hr> elements through jQuery when class starts with line-rooms-sphere. <hr> elements have more than one class.
This is my html:
<hr class="line-rooms-sphere-4 rooms-hidden"/>
// There are 5 hr like this one
This is my jquery code:
$('hr [class^="line-rooms-sphere"]') // => Not working, Why?
$('[class^="line-rooms-sphere"]') // => This Works well
I want to get all the <hr> elements when they have the wanted class (in this case, starting with line-rooms-sphere).
Any help? Thanks
Your first example:
$('hr [class^="line-rooms-sphere"]') // => Not working, Why?
Does not work as you have a space between the hr and the attribute selector. The jQuery selector engine follows CSS rules, so a space means that the second rule should be looked for within the first selected element.
Instead the attribute you want is on the hr itself, so no space is required:
$('hr[class^="line-rooms-sphere"]');
There should be no space between "hr" and "[class... ]" in the selector "$('hr [class^="line-rooms-sphere"]'". Check this snippet.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<hr class="line-rooms-sphere-4 rooms-hidden"/>
<hr class="line-rooms-sphere-4 rooms-hidden"/>
<hr class="line-rooms-sphere-4 rooms-hidden"/>
<script>
$(document).ready(function(){
$('hr[class^="line-rooms-sphere"]').css("border-width","8px");
});
</script>

How to get div text value?

I've got the following html:
<div class="question">
<div class="text">
Blah Blah
</div>
</div>
I am trying to get the value "Blah Blah" using javascript.
So something like?
alert(document.getElementsByName("question")[0].value);
document.getElementsByClassName('question')[0].innerText;
or
document.querySelector('.question').innerText;
You can do it like this
alert(document.getElementsByClassName("question")[0].children[0].innerHTML);
You need to select the element correctly first. It doesn't (and can't) have a name attribute so getElementsByName is wrong. You can use getElementsByClassName or (with more limited support) the new and shiny querySelector:
var div = document.querySelector('.question');
Then you need to get it's "value". It isn't a form control so it doesn't have a value property. It has childNodes, the one of which you care about is another div.
var childDiv = div.querySelector('.text');
You can skip the two stages if you are are using querySelector and just use a descendant combinator:
var childDiv = document.querySelector('.question .text');
This child div then has another child node, but it is a text node rather than an element node. You can get it like so:
var textNode = div.firstChild;
Finally you can get the text in a textNode using the data property.
var text = textNode.data;
And if you put it all together:
alert(document.querySelector('.question .text').firstChild.data);
Such: http://jsfiddle.net/LR93S/
No need to rely on jQuery here, use innerText
document.querySelectorAll('div.question')[0].innerText
$('.question').text(); // jquery
document.getElementsByClassName("question")[0].innerText; // javascript
Try this: document.getElementsByClassName("text")[0].innerHTML (http://jsfiddle.net/hv9Dx/15/)
The simplest way to do this is with jquery:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
var divvalue = $('.text').html()
alert (divvalue);
You could also change your html to use an ID
<div class="question">
<div id="text">
Blah Blah
</div>
</div>
and use:
document.getElementById("text").innerHTML;
Example: http://jsfiddle.net/DanBrown180/N9Z8Z/
document.querySelectorAll('.text')[0].innerHTML
For the following example:
<div class="question" id="question">
<div class="text" id="text">
Blah Blah
</div>
</div>
You can try to get the value of its inner div tag like this:
alert(document.getElementById('question').childNodes[1].innerHTML);
Cheers!
Use the standard DOM property textContent, which is widely supported and standardized, unlike innerText:
document.getElementsByClassName("question")[0].textContent;
If you need to support IE <= 8 then you've got two problems: neither document.getElementsByClassName() nor textContent is supported.
For the first issue, it's not too hard to write/find a function to retrieve elements by class name using other DOM methods (example).
For the second, you can use IE's innerText property, which will do roughly (but not precisely) the same thing as textContent.

How do I find a specific child element using javascript

I've just started using javascript and am trying to do the following:
My html doc contains divs and span elements like below.
I want to create a variable which will store the value of my-new-id for a specific div child element.
The only information I have to go on, is that I always know what the span text will be cause it's based on a username.
Therefore, how would I get the value of my-new-id for user1?
I have already figured out how to navigate to the correct div elemenet using the document.getElementById method. I then try to use a jquery selector such as :contains, but get stuck.
Many thanks on advance.
<div id=1>
<span my-new-id=x>user1</span>
<span my-new-id=y>user2</span>
<span my-new-id=z>user3</span>
</div>
<div id=2>
<span my-new-id=x>user10</span>
<span my-new-id=y>user1</span>
<span my-new-id=z>user30</span>
</div>
Using jQuery:
var val = $('span:contains("user1")').attr('my-new-id');
A couple of additional points:
Do not use IDs that begin with a number. This is not allowed in the HTML4 spec, and can cause unexpected behavior in some browsers. Instead, prefix your ID's with an alphabetic string, like this:
<div id="container1">
...
</div>
I would recommend that you use data-* attributes instead of making up non existent attributes. You can make data attributes like this:
<span data-new-id="x">user1</span>
You can then retrieve this value using:
$('span:contains("user1")').data('newId');
Note that the attribute name has been stripped of dashes and camel-cased.

Categories

Resources