Find css class on div and get values - javascript

I'm trying to find a class on a div (where the value will always end in 0bg), given a partial string, and then get its background style value.
For example:
.xx-color-100bg{
background-color: #323334;
}
<div class="heading xx-color-100bg"></div>
document.querySelectorAll(".heading").classList.contains("0bg").style.background
The solution above errors with Cannot read properties of undefined (reading 'contains')
How can I find the necessary class and grab it's background-color value?

querySelectorAll() returns a NodeList, so you can't use classList. You need to loop over the DOMElements in the list or just assume the first one is what you need:
document.querySelectorAll(".heading").forEach(e => {
// do something with e.classList
});
// OR
document.querySelectorAll(".heading")[0].classList // the first element

Figured out the solution right after posting the question:
window.getComputedStyle(document.querySelector(".heading[class*='0bg'")).backgroundColor;

Related

Getting all selectors and printing its value to console

I am on the following site : Betway and want to extract via a query all the values from the selector collectionitem with the class oneLineEventItem.
I can partially get this with the following:
document.querySelectorAll("div[collectionitem] ~ .oneLineEventItem").forEach((result) => {
console.log(result)
})
However I have noticed the following issues with this:
It selects n-1 such that the first is not selected.
It prints the node tree and not just the values.
How do I correctly select all and print the values out?
Using the General sibling combinator (~) is not the good approach. To select all div elements having the attribute collectionitem and the class oneLineEventItem you should use the following selector :
div[collectionitem].oneLineEventItem
Then, as I said in my comment, you can get the value of the collectionitem attribute using the getAttribute() method :
document.querySelectorAll("div[collectionitem].oneLineEventItem").forEach((result) => {
console.log(result.getAttribute("collectionitem"));
})
<div collectionitem="test1" class="oneLineEventItem">foo</div>
<div collectionitem="test2" class="oneLineEventItem">bar</div>

How to change a style property of element by class name without any use of ID's in JS?

I am doing a school project and it's my first time using JS, and we are not allowed to use any ID's for css styling, but on some event that the user does I want to change the style of a div in the page:
HTML:
<div class="ads">
...
</div>
CSS:
.ads{
display:block;
//and some other style properties
}
and when the user do the event I want to change the display property into :
display : none;
I know how it can be done using ID for the element, but how can it be done only by a class name?
I would like to be able to do it something like this:
document.getElementsByClassName('ads').style.display=none;
Thank you.
If you know that there is only one element with that class, use the first element of the NodeList that document.getElementsByClassName returns:
document.getElementsByClassName('ads')[0].style.display = 'none';
document.getElementsByClassName('ads')[0].style.display ='none';
If you have just a one element with class"ads", you can use:
document.querySelector('.ads').style.display='none'
Else, if you have more than one element you can add a unique class name for you element like this
<div class="ads foo">
and using document.querySelector('.foo').style.display='none'
for changing it's style.
You should put index, also the string after the equal sign must be with quotation marks, like below:
document.getElementsByClassName('ads')[0].style.display="none";
w3schools
The NodeList object represents a collection of nodes. The nodes can be accessed by index numbers. The index starts at 0.

Change CSS attributes on part of a HTML element's innerHTML with Javascript

I have been trying to find a way to change part of the innerHTML of several elements with the class .studentYear, but I keep getting a JavaScript undefined error. Here's what I am trying.
JavaScript:
document.getElementsByClassName('studentYear').innerHTML.indexOf(" ").css('color', '#800000');
HTML:
<div class="accordionContainer">
<div class="studentYear">Freshman (A1 Schedule)</div>
<div class="accordionContent" style="display:none;">
<p class="studentTerm">Fall</p>
<p>Content</p>
</div>
</div>
I see now that it is a collection (array type). I need to access the innerHTML for each item in the collection and change the style attribute on only part of the innerHTML, in this case everything in parentheses "(A1 Schedule)". I still get the undefined error if following the suggestions made below.
There are a number of problems with what you're trying.
document.getElementsByClassName returns an HTMLCollection, which is kind of like an array, but not quite, so you can't call innerHTML on it directly
indexOf(" ") will give you the first index of the space, which would possibly be before the element. It would also give you a number.
css() doesn't exist in vanilla JavaScript, that's a jQuery thing.
It looks like you're wanting to set that element to use color: #000000. That means you actually need to set the style attribute.
This code would do the trick, applying it to every one of them with the class studentYear.
Array.prototype.forEach.call(document.getElementsByClassName('studentYear'), function (element) {
element.style = 'color: #F00';
});
The Array.prototype.forEach.call lets us treat the HTMLCollection as an array and loop through it. Then for each element, we'll set it's style attribute to color: #F00 (or whatever you want, I used red to make it obvious).
If you need to support older browsers, you shouldn't access the style attribute directly, instead use setAttribute instead:
element.setAttribute('style', 'color: #F00');
As the comments have said, you have to loop through the objects and set each one since it is similar to an array. Something like this:
var items = document.getElementsByClassName('studentYear');
for (var i = 0; i < items.length; i++) {
items[i].setAttribute('style', 'color: #F00');
}
Edit: Just saw samanime's answer, which seems a little more elegant in my opinion.

Select all the elements within an element having an attribute set to a specific value

I have the followings defined :
var excludedFiltersPanel = $("#excludedFiltersPanel");
var includedfiltersPanel = $("#includedfiltersPanel");
where *Panel is just a div.
in excludedFiltersPanel there are some div's with attribute data-iscorefilter="true" e.g. :
<div id="filterPanel-LastName" class="filterPanel" data-iscorefilter="true">
<Some Stuff here!>
</div>
I am trying to get them and move them to includedfiltersPanel:
It seems neither of these is a correct syntax:
excludedFiltersPanel.('[data-iscorefilter="true"]')
excludedFiltersPanel.$('[data-iscorefilter="true"]')
1.What is the correct syntax?
2.How do I append them to includedfiltersPanel? (I know how to append a single item, but not sure what is the common good practice here, e.g. using for loop or some JQuery magic)
Since excludedFiltersPanel there are some div's with attribute data-iscorefilter="true"
Use .find()
Description: Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element.
It would look like :
excludedFiltersPanel.find('[data-iscorefilter="true"]')

JavaScript equivalent to JQuery .next()

Is there a JavaScript method similar to jQuery .next()? I want to find the next element that has the class of "error" relative to the element. I've tried using .nextSibling as a loop but couldn't figure it out. Didn't know if there was an easier way to go about it without jQuery.
For instance, if I have this code:
<div id="section">
<div id="test">test</div>
<span class="info">Information</span>
<span class="error">Error!</span>
</div>
I'm trying to get the next .error class closest to #test, if I have a #section2 and a #test2 I would want to get the .error class closest to #test2 and so on.
The nextElementSibling property returns the element immediately following the specified element, in the same tree level.
Example: Get the HTML content of the next sibling of a list item:
var x = document.getElementById("item1").nextElementSibling
The nextElementSibling property might help.
Best bet would be to search through the jQuery code and see what they did.
http://code.jquery.com/jquery-2.0.3.js
At a glance, I do see some calls to "nextSibling" and "previousSibling."
Also see here:
How to get next element using JavaScript-only?
Hope this helps!
This is the pure javascript for you:
HTML
<div id="nodes">
<div class="error">This is error Node</div>
<div class="nextElement">This is next Element</div>
</div>
Javscript:
var nodes = Array.prototype.slice.call( document.getElementById('nodes').children ),
errorNode = document.getElementsByClassName('error')[0];
var indexOfError = nodes.indexOf(errorNode);
var nextElement = nodes[indexOfError + 1];
alert(nextElement.innerText);
Here is demo
Sounds like you may be looking for document.getElementsByClassName()... if the elements with class=error are not direct siblings in the DOM, then there's not a good way to find them otherwise. It's elementary, but you can just search through the array returned by document.getElementsByClassName('error') until you find your starting element, and then you know the next item in the array will be the next element in the DOM.
See also MDN reference. Won't work in old IE, but works for all modern browsers.

Categories