What is being computed in this stylesheet? [duplicate] - javascript

This question already has answers here:
What do querySelectorAll and getElementsBy* methods return?
(12 answers)
Closed 6 years ago.
I'm trying to use
onmouseover="document.getElementsByClassName().style.background='color'"
to change the color of all divs with a given classname to another color when hovering over another page element.
Here is a jsfiddle -if anyone could give a few helpful pointers as to where I'm going wrong that would be great, I'm sure it's something really obvious that I'm missing. It worked with document.getElementById, but that only changed the color of the first div, not all of them.
Thanks :)

As the function name suggests getElementsByClassName returns a collection not just one object. So you need to loop through them and apply the color to it.
document.getElementsByClassName()
^_______
Plus your id part is invalid. Id cannot have spaces and also it shouldn't appear again on the page which is violated by:
<th id="colorswitcher A" onmouseover="document.getElementsByClassName('a').style.background='red'">a</th>
<th id="colorswitcher B" onmouseover="document.getElementsByClassName('a').style.background='blue'">b</th>
You can do it this way (You can look up what is a handler and try play yourself with it.), don't use inline attributes for handlers.
window.onload=function(){
var aColl = document.getElementsByClassName('a'); //Cache the collection here, so that even a new element added with the same class later we can avoid querying this again by using the cached collection.
var bColl = document.getElementsByClassName('b');
document.getElementById('A').addEventListener('mouseover', function(){
changeColor(aColl, 'red');
});
document.getElementById('B').addEventListener('mouseover', function(){
changeColor(bColl, 'blue');
});
}
function changeColor(coll, color){
for(var i=0, len=coll.length; i<len; i++)
{
coll[i].style["background-color"] = color;
}
}
Fiddle
If you are really trying to do it for some real work, then don't change the style attribute, instead define classes and add/remove classes on mouseover, mouseout events so that you get the power of css' cascading property.

Related

how can i change this span text using JS [duplicate]

This question already has answers here:
What do querySelectorAll and getElementsBy* methods return?
(12 answers)
Closed last month.
i tried to change this text using getElementsByTagName() but it did not work i do not know what is the probleme
enter image description here
getElementsByTagName()
You should check the DOM documentation because you are misunderstanding what that function does, getElementsByTagName("s-button-text") isn't getting the element because thats not how it works.
This would work getElementsByClassName("s-button-text") or getElementsByTagName("span"), tag refers to the <span> in this case, and class refers to the class=" attribute.
I would highly recommend you don't use the second one as it will get other <span> elements in the page and not just the one you want.
As well, even if you replace that it will create an error, this is how to do what you want to do:
function change_content() {
let elements = document.getElementsByClassName('s-button-text');
for (let i=0; i<elements.length; i++) {
elements[i].innerHTML = "newText";
}
}
getElementsByTagName() returns an array of elements by tag name. You are trying to get an element by it's class so you need a different method. You can use querySelector() or querySelectorAll().
querySelector() is used to find a single element by a CSS selector.
querySelectorAll() is used to get a list of elements by a CSS selector.
This will find all elements with this class name and change the text of the first element returned:
document.querySelectorAll('.s-button-text')[0].textContent = 'New text';

Click on multiple elements same class name [duplicate]

This question already has answers here:
What do querySelectorAll and getElementsBy* methods return?
(12 answers)
Closed 4 years ago.
I have multiple html elements with same class name i want to know which element clicked in pure javascript
link a
link a
link a
in javascript i tried a lot of solutions but all i found working with one element only
what i wrote so far
var dd = document.getElementsByClassName('messages-email');
dd.onclick() = function(ee){
// if i clicked the first link i want to get data-wow which is 1
// and if i clicked the third one i wanna get data-wow which is 3
console.log('i want the clicked elemet attribute ')
}
There are a few issues with your code:
There is no element with the class message-email in your markup. I suppose it's simply a mistake when you're attempting to demonstrate your markup, and that you are referring to the anchor elements with the wow class
document.getElementsByClassName returns a Node collection. You will have to iterate through the collection in order to bind the click event. You can use Array.prototype.forEach.call(<NodeCollection>, function(element) { ... }) to iterate through your node collection
Do not use .onclick to bind click event, as that will override any onclick handlers. You should be using .addEventListener('click', function() {...}) instead
In order to access data-wow attribute, use the HTML5 dataset API
With that in mind, here is a proof-of-concept example:
var dd = document.getElementsByClassName('wow');
Array.prototype.forEach.call(dd, function(element) {
element.addEventListener('click', function() {
console.log('data-wow value is: ' + element.dataset.wow);
});
});
link a
link a
link a
Bonus: If you are familiar with ES2015 (aka ES6), there is an even easier way to do this:
const dd = document.getElementsByClassName('wow');
Array.from(dd).forEach(element => {
element.addEventListener('click', () => {
console.log('data-wow value is: ' + element.dataset.wow);
});
});
link a
link a
link a

Change Multiple Classes with the same name using JavaScript?

Check out my small project on codepen below...
http://codepen.io/ajduff14/pen/DlHge
Basically I'm just testing out my JavaScript knowledge and I want to learn how to change all the buttons to the same class and use JavaScript to input a color that will change the background color of all the buttons with the given class "buttons". I can only manage to get it to work for 1 class at a time but not several.
It's probably a simple answer but I've done quite a bit of digging for it already and I can't find one! Could someone please help?
Thanks,
Adam
There is no way to change classes or styles on many elements at the same time, you'll have to iterate and apply it to one element at a time
var buttons = document.querySelectorAll('.buttons');
for (var i=0; i<buttons.length; i++) {
buttons[i].style.background = 'red';
buttons[i].className = buttons[i].className + ' newclass';
}
There were some trivial mistakes in your HTML and JS code.
1) In many places, instead of class="buttons" for input tag, you specified it as id="buttons". Remember that you should have a unique id for each element.
2) You were setting the style.backgroundColor property for buttons[3] and not for all objects with class name buttons.
document.getElementsByClassName('buttons') gets you an array of objects with class name "buttons." You need to iterate over every element of this array and set its background color property to appropriate value.
You could use a for-in loop or a standard for loop to achieve this purpose. I have used the for-in loop.
for (button in buttons) {
buttons[button].style.backgroundColor = div2.children[0].value;
}
See this link for a working copy of your project: http://jsfiddle.net/mayank_agarwal/LaQuz/

select html object without id

Edit: one missing piece of information - I can't use the class selector because there are more divs with the same class. I already thought of that, but I forgot to mention it. I have no idea why my post got downvoted, but it seems awfully silly considering I provided a lot of information, gave it honest effort, and tried to be verbose with code examples. People on this forum are ridiculous sometimes.
I'm trying to set the id of a div that doesn't have one and there's no way I can give it one upon generation of the page. I've tried using jquery (.each, .contains, .find, .filter, etc.) and I can't seem to get it right. I know a ton of people have asked this question, but none of the answers made sense to me.
I have the ability to set the text (html?) of the div, but nothing else. It ends up looking like this:
<div class="dhxform_note" style="width: 300px;">Remaining letters: 500</div>
I want a handle to the div object so I can show the user how many more letters they can type by updating the text.
Using this:
$("div")
returns a list of all divs on the page. I can see the target div in the list, but I can't get jquery to return a single object.
I know it can also be done with something like this:
var divs = document.getElementsByTagName("div");
for(var i = 0; i < divs.length; i++) {
if( /^Remaining letters/.test(divs[i].innerText) )
divs[i].id = "kudosMsgNote"
}
}
but I was hoping to complete this with a cleaner looking solution involving jquery. I also simply want to know how to do it with jquery, aesthetics not withstanding.
Use a class selector.
var theDivViaTheClass = $(".dhxform_note");
Class Selector (“.class”)
Description: Selects all elements with the given class.
version added: 1.0
jQuery( ".class" )
class: A class to search for. An
element can have multiple classes; only one of them must match.
For class selectors, jQuery uses JavaScript's native
getElementsByClassName() function if the browser supports it.
You seem to be targeting the <div> by its text. Try using the :contains selector:
$("div").filter(':contains("Remaining letters")').first().attr("id", "kudosMsgNote");
The .first() is to make sure you don't set the same id for multiple elements, in case multiple elements contain the text "Remaining letters".
Here's the docs for the :contains selector: http://api.jquery.com/contains-selector/
Be careful, the text you're looking for is case sensitive when using :contains!
Is that div the only one with the class dhxform_note? If so, you can use the class selector:
$('.dhxform_note').html();
With jQuery, you can specify any css selector to get at the div:
$(".dhxform_note").attr("id", "kudosMsgNote");
will get you this element as well.
Selecting on inner text can be a bit dicey, so I might recommend that if you have control over the rendering of that HTML element, you instead render it like this:
<div name="remainingLetters" class="dhxform_note" style="width: 300px">Remaining Letters: 500</div>
And get it like this:
$("[name=remainingLetters]").attr("id", "kudosMsgNote");
However, it's possible that you really need to select this based on the inner text. In that case, you'll need to do the following:
$("div").each(function() {
if ( /^Remaining letters/.test($(this).html()) ) {
$(this).attr("id", "kudosMsgNote");
}
});
If you cannot set id for whatever reason, I will assume you cannot set class either. Maybe you also don't have the exclusive list of classes there could be. If all those assumptions really apply, then you can consider down your path, otherwise please use class selector.
With that said:
$("div").filter(function() {
return /^Remaining letters/.test($(this).text())
}).attr('id', 'id of your choice');
For situations where there are multiple divs with the class dhxform_note and where you do not know the exact location of said div:
$("div.dhxform_note").each(function(){
var text = $(this).text();
if(/^Remaining letters/.test(text)){
$(this).attr("id", "kudosMsgNote");
}
});
EXAMPLE
If, however, you know that the div will always be the 2nd occurrence of dhxform_note then you can do the following:
$("div.dhxform_note").get(1).id = "kudosMsgNote";
EXAMPLE
Or do a contains search:
$("div.dhxform_note:contains('Remaining letters')").first().attr("id", "kudosMsgNote");
EXAMPLE

Is it possible transform one DOM element to another? Or copy all attributes from it? [duplicate]

This question already has answers here:
How to copy all the attributes of one element and apply them to another?
(12 answers)
Closed 3 years ago.
Is it possible transform one DOM element to another?
By jQuery or even by JavaScript.
I just to want for example:
get table > thead > tr > th's with all classes, attributes, properties and put it in table > body like as tr > td.
Or maybe is another way for that?
You have a couple options.
You can use jQuery's clone(), which will copy everything on/in the DOM node. Then use append() to attach the clone to whatever element you want it moved to. Then just remove the original node.
If you just want the attributes from the DOM node (classes, id, etc.) then you can use the attributes array that is present on all DOM nodes. You'd have to loop through each attribute and then set it on the new element individually though. I have yet to find a simple way to just copy everything over. In vanilla Javascript that would look something like this:
var originalELement = document.getElementById('original-element-id');
var newElement = document.createElement('div');
for (var i = 0; i < originalElement.attributes.length; i++) {
var attr = originalElement.attributes.item(i);
newElement.setAttribute(attr.nodeName, attr.nodeValue);
}
when you do element1.append(element2) element2 will move inside element1. append or appendChild. weird but true. append actually means "cut"

Categories

Resources