JavaScript: Select an element to a div and update styling - javascript

I need to add styling to a DIV element using JavaScript. I have the following DIV in my document:
<div class="RnEpo Yx5HN " role="presentation">
The script that I have tried is:
WebElement = document.querySelectorAll("div[class='RnEpo Yx5HN ']");
WebElement.style='height: 10000px;'
WebElement.setAttribute("height = 1000px;");
I want to achieve the same styling as this CSS:
.RnEpo Yx5HN
{
height: 100000px;
}

To achieve what you require, first replace querySelectorAll() with querySelector() seeing that your only need to select the first matching element.
Consider also revising your selector from div[class='RnEpo Yx5HN '] to a more robust selector in the form of div.RnEpo.Yx5HN which is to say:
Select div elements that have classes any ordering of class RnEpo and Yx5HN
Lastly, revise the way that you're applying the inline style so that the height attribute is directly specified on the WebElement style object.
These changes make the call to setAttribute() redundant. Note also that; setAttribute() takes two arguments, and the DIV element does not have a native height attribute.
Here's a working snippet showing this in action:
/* Use querySelector() to select first matching element and use dot notation syntax to select div with both classes */
const WebElement = document.querySelector("div.RnEpo.Yx5HN");
/* Apply inline style, avoid invalid setAttribute call */
WebElement.style.height = `10000px;'
<div class="RnEpo Yx5HN" role="presentation">

Related

How add ID to HTML href with javascript

I have an HTML like this
<div class="this">
EXP
</div>
I want to add id to <a>. But do not know what to do.
First select your element using something like .getElementsByClassName(). Keep in mind that .getElementsByClassName() returns a NodeList collection of elements, so you'll want to access the first index (or loop over them). You can then simply set the ID with .id, as the ID is merely a property of an element.
This can be seen in the following:
const element = document.getElementsByClassName('this')[0];
element.id = 'element';
console.log(element);
<div class="this">
EXP
</div>
If you want to add this with Javascript, you'll need to use a selector to target your <a> tag and then set the id attribute on it. You can do this by using the querySelector() function or as seen below:
// Find an <a> tag that occurs below a class called "this" and set its id attribute
document.querySelector('.this > a').id = "some-id";
There are many other available functions to handle this through native Javascript and other frameworks, so your milage may vary depending on what you are using.
Example
In this example, we have provided some CSS that should only apply to an element with an id of "test" and we'll run the necessary code to show that the id is being added to the element (as it will be red):
document.querySelector('.this > a').id = 'test';
#test { color: red; }
<div class="this">
EXP
</div>
Add the id attribute to the <a> tag. See the differences of the middle line:
<div class="this">
<a id="expid" href="exp.com">EXP</a>
</div>

HTML/JS referencing IDs

I'm wondering how to reference an HTML id or a class in JavaScript in the following context.
<script type="text/javascript">
(function() {
var menu = document.querySelector('ul'),
menulink = document.querySelector('**REFERENCE CLASS**');
menulink.addEventListener('click', function(e) {
menu.classList.toggle('active');
e.preventDeafult();
});
})();
</script>
I'd appreciate any help I can get, thanks.
Let's say you have an element with class attribute equals to "my-class" and you want to select that element with JavaScript. Here as an example i'll select an element based on its class attribute and change his color to green using only JavaScript.
// referencing the element with class attribute containing my-class using querySelector() method that you used it in your code, notice the " . " (dot) before the class-name
var myClassDiv = document.querySelector('.my-class');
// changing the text color to green
myClassDiv.style.color = '#0F0';
<div class="my-class">by default my color is black but JavaScript made me green !</div>
Explanation:
The method querySelector() receives a string representing a fully qualified CSS selector. i.e querySelector('body #main > ul.menu > li.class-name') and as the same selector can match many elements in the same document this method returns only the first element matched by the selector.
To get all the elements matching a selector you could use querySelectorAll() that returns an array of the matched elements.
You wanted to select an element based on it's class-name, JavaScript provides a method that fetches all the elements based on a class-name: getElementsByClassName() that returns an array containing the matched ones even if there is only one element. It rereceives a string representing a class-name, NOT as you write it in CSS i.e getElementsByClassName('class-name') NO dot before the class-name.
To do the same task as we did in the top of that answer
, I'll be using the getElementsByClassName() instead of querySelector().
// referencing the element with class attribute containing my-class
var myClassDiv = document.getElementsByClassName('my-class')[0];
// changing the text color to green
myClassDiv.style.color = '#0F0';
<div class="my-class">by default my color is black but JavaScript made me green !</div>
Hope I pushed you further.

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.

How to use js to query shadow dom element in Polymer?

I know how to query shadow dom element in <style> tag,but i want to use data-bind dynamically change the style,data-bind can not be applied in <style> in Polymer,so i should make it happen in js.For example,i use core-scroll-header-panel component, i can query its background style using:
<style>
core-scroll-header-panel::shadow #headerBg {
background: #5cebca;
}
</style>
but how can implement it in js?
Here's the way to select your element:
var shadow = document.querySelector('core-scroll-header-panel').shadowRoot;
var header = shadow.querySelector('#headerBg');
Note that it will return one single element. If you need to loop over multiple element you may use querySelectorAll as you probably know.
You can then change your background color as normal:
header.style.backgroundColor = "#5cebca";
However, changing a color in directly in JavaScript is not adviced and you should use CSS for that.
header.className = "my_css_class";
Note that it will return one single element. If you need to loop over multiple element you may use querySelectorAll as you probably know.
I have tried it out :
document.querySelector('core-scroll-header-panel::shadow #headerBg');
and is there any else solutions?

How to add `style=display:"block"` to an element using jQuery?

How to add style=display:"block" to an element in jQuery?
$("#YourElementID").css("display","block");
Edit: or as dave thieben points out in his comment below, you can do this as well:
$("#YourElementID").css({ display: "block" });
There are multiple function to do this work that wrote in bottom based on priority.
.css()
Set one or more CSS properties for the set of matched elements.
$("div").css("display", "block")
// Or add multiple CSS properties
$("div").css({
display: "block",
color: "red",
...
})
.show()
Display the matched elements and is roughly equivalent to calling .css("display", "block")
You can display element using .show() instead
$("div").show()
.attr()
Set one or more attributes for the set of matched elements.
If target element hasn't style attribute, you can use this method to add inline style to element.
$("div").attr("style", "display:block")
// Or add multiple CSS properties
$("div").attr("style", "display:block; color:red")
JavaScript
You can add specific CSS property to element using pure javascript, if you don't want to use jQuery.
var div = document.querySelector("div");
// One property
div.style.display = "block";
// Multiple properties
div.style.cssText = "display:block; color:red";
// Multiple properties
div.setAttribute("style", "display:block; color:red");
Depending on the purpose of setting the display property, you might want to take a look at
$("#yourElementID").show()
and
$("#yourElementID").hide()
If you need to add multiple then you can do it like this:
$('#element').css({
'margin-left': '5px',
'margin-bottom': '-4px',
//... and so on
});
As a good practice I would also put the property name between quotes to allow the dash since most styles have a dash in them. If it was 'display', then quotes are optional but if you have a dash, it will not work without the quotes. Anyways, to make it simple: always enclose them in quotes.
If you are using BS5 and Tabulator I found that I had to add position: static to the cell AND add it to the button.
So, I added the following CSS:
.table-responsive .dropdown,
.table-responsive .btn-group,
.table-responsive .btn-group-vertical {
position: static;
}
and on the Tabulator div I have:
<div id="myTable" class="table-sm table-responsive"></div>
and finally on the event I do:
myTable.on("dataProcessed", function(data){
$('[tabulator-field="my_fancy_field"]').css("position", "static");
});
You will need some way of finding the right cell. I used the field that I am loading the data from.
I then end up with (on most rows) something that looks like this:
And on the last row it pops upwards like this:

Categories