Remove randomly generated class and id in with Javascript? - 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')

Related

Get dynamic elements by the middle/End of it's class name

I need to find a group of elements by the end of their class names, it's highly similar to this Get element by part of Name or ID however using document.querySelectorAll([class~=<constant string>]) does not work but [class=<full class name including randoms chars (see below) does work.
The elements in question have a class name like. (random string of three chars)-(Some constant String) is it possible to find them by the (some constant string)?
The correct syntax is $= to find a class that ends with a particular string.
If you want to use a variable in that selector use a template string to insert it.
const constant = '123';
const divs = document.querySelectorAll(`[class$="${constant}"]`);
divs.forEach(div => console.log(div.textContent));
<div class="abc-123">Will be selected 1</div>
<div class="def-234">Will not be selected 1</div>
<div class="ghi-123">Will be selected 2</div>
<div class="jkl-234">Will not be selected 2</div>

Using a variable value on multiple elements with the same iD

So I have a file like
<div class="u1">
<p id="level1"></p>
<p id="level2"></p>
</div>
<div class="u2">
<p id="level1"></p>
<p id="level3"></p>
</div>
and if I use something like
document.getElementbyId("level1").innerText(or innerHtml) = "Hello"
it writes that string on one element, and not on every element with id="level1"
I tried with
$('#level1').text("Hello");
but it works only for one.
I need something to write a string on every element with id="level1".
ID is a unique identifier, so you can't have few items with the same ID. Provided HTML code is invalid. You can use CLASS attribute or data-id or....
If you can't change HTML and it comes from third-party dependency, then we have a list of NOT recommended but WORKING solutions
jQuery:
$('[id="level1"]').text("Hello");
js:
var elements = document.querySelectorAll('#level1'); + for loop to iterate elements
And a lot of similar solutions based on knowledges how elements selecting works under the hood
It is ideal to have Unique Ids and thus you cannot update it this way. What you can do is you can give it a class like this:
<div class="u1">
<p id="level1" class="helloText"></p>
<p id="level2"></p>
</div>
<div class="u2">
<p id="level1" class="helloText"></p>
<p id="level3"></p>
</div>
Now use this JS to update the HTML:
var paras = document.getElementsByClassName("helloText");
for (i = 0; i < paras.length; i++) {
paras[i].innerHTML = "Hello";
}
You can also remove the Ids or make them unique to make your code cleaner. It is never recommended to use duplicate Ids.
You give a classname to the elements you need:
class = "levels"
in the script, use document.getElementsByClassName, which return an array with all elements. then you can loop through that array to get the info of each elements.
let levels = document.getElementsByClassName("levels");
for (let j=0; j<levels.length; j++){
levels[j] do something...;
}

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"]');

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.

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

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>

Categories

Resources