This is my code.
var hitButton = document.querySelector('.btn-hit');
var scoreResults = document.querySelectorAll(".flex-blackjack-row-1 h3");
var scores = document.querySelector(".flex-blackjack-row-1 span");
const config = {childList: true};
const bustedMessage = document.createElement('h2');
bustedMessage.textContent = 'BUSTED!';
const busted = function (mutationList, observer){
if (parseInt(scores.textContent) > 21) {
console.log(scores.textContent)
scoreResults[0].before(bustedMessage);
hitButton.setAttribute('disabled', 'true');
}
}
const observer = new MutationObserver(busted);
observer.observe(scores, config);
In that callback function named "busted", I'm adding an attribute to "hitButton". But when I try to update it like this in another function
hitButton.setAttribute('disabled', 'false');
it is not being updated.
But I can remove that attribute using
hitButton.removeAttribute('disabled');
Removing that attribute is doing what I want to do. But now I need to know, why can not I update it instead of removing?
Because, these attributes in HTML tags are just boolean attributes. Say for e.g., if "disabled" attribute is present, it tells the browser to disable it regardless of the value you are setting to it.
"checked", "disabled", "selected", "muted", "autoplay", "loop", "controls" are some of the boolean attributes in HTML.
Google "Boolean attributes in HTML". You will learn more about it. Hope it answers your question.
Related
here is a website https://secure.givelively.org/donate/lifesteps
I want to type custom values here with simple js/jquery
It doesn't work when we click on continue
i tried
document.querySelector("#custom-input-element").click()
and
document.querySelector("#custom-input-element").focus()
and
document.querySelector("#custom-input-element").value='1';
all of them not worked
let elem = document.getElementById("custom-input-element");
const prevVal = elem.value;
elem.value = 1;//Your Value
elem._valueTracker.setValue(prevVal);
let event = new Event("input", { target: elem, bubbles: true });
elem.dispatchEvent(event);
try
$('#custom-input-element').click(() => console.log(clicked));
i just used this on my machine to make sure it works, or make sure the html id is not misspelled
I'm studding HTML, CSS and JS and while I was creating an exercise, I was forced to stop due to an error. I created an button dynamically, setted an onclick to it and then created a function with that onclick. The problem is that the function isn't working, at leats it doesn't made anything till now.
let formularys = document.querySelector('section#formulary')
let slct = document.createElement('select')
let opts = document.createElement('option')
let optp = document.createElement('option')
let fbtn = document.querySelector('input#formularybtn')
let nbtn = document.createElement('input')
let br = document.createElement('br')
slct.id = 'pors'
slct.size = '2'
opts.value = 'rsite'
opts.innerHTML = 'Rate site'
optp.value = 'rp'
optp.innerHTML = 'Rate products'
nbtn.setAttribute('type', 'button')
nbtn.setAttribute('value', 'Next')
nbtn.setAttribute('onclick', 'nbutton')
function nbutton(){
console.log('Next working')
/*if(slct.selectedIndex == 1){
console.log('Valid rate choose')
}*/`enter code here`
}
instead of using setAttribute you can just do
nbtn.onclick = nbutton
in javascript, onclick isn't a string but a function.
The problem is, you are not appending your html code generated from JavaScript to DOM. You can either append to main DOM like below
document.body.appendChild(nbtn);
document.body.appendChild(optp);
or you can append them to some parent div by first getting div id
document.getElementById("divId").appendChild(nbtn);
where divId is id of your div where you want to add this html.
Also you should assign event listener in correct way as suggested by Tony and Rashed Rahat.
Try:
element.onclick = function() { alert('onclick requested'); };
This is very odd, I'm getting videos via document.getElementsByTag('video') and I can't change their width nor any other value.
Here's the Javascript code I'm using -
window.onload = function() {
this.videos = document.getElementsByTagName('video');
var self = this;
for(var i=0;i<videos.length;i++) {
videos.item(i).addEventListener("loadedmetadata",
(function(index){
return function() {
console.log(self.videos[index].offsetWidth); //shows X
self.videos[index].offsetWidth = "480";
console.log(self.videos[index].offsetWidth); //shows X
}
})(i)
);
}
}
Example <video> tag -
<video><source src="videos/video_1.mp4" type="video/mp4"></video>
I have no idea what it is happening and I've never encountered such kind of problem.
Thanks
EDIT:
Using the setAttribute function just adds it to the live html, but the size isn't really changing
The offsetWidth is a read-only DOM property so you can not update it. However why not change the element width?
window.onload = function() {
this.videos = document.getElementsByTagName('video');
var self = this;
for(var i=0;i<videos.length;i++) {
videos.item(i).addEventListener("loadedmetadata",
(function(index){
return function() {
self.videos[index].width = "480";
}
})(i));
}
}
You can take into account the borders, paddings, margins...
Note there is a difference between three things you are conflating into one:
HTML attributes
DOM properties
CSS styles
This is an HTML attribute:
If you have a DOM element representing an HTML tag, you can modify the attributes like so:
var a = document.createElement('a')
a.setAttribute('href', "http://example.com")
This is a DOM property:
var a = document.createElement('a')
a.href = "http://example.com"
Note how a DOM property can be similarly named to an HTML attribute, but they are not the same thing. Oftentimes, changing an HTML attribute will modify the corresponding DOM property, but not vice versa. Also, not all attributes have matching properties, and so on.
CSS styles are accessed via the DOM property style(which corresponds to the HTML attribute style, but while the HTML attribute style is a string, the DOM property is an object):
var a = document.createElement('a');
a.style.width = "500px";
a.style.height = "20%";
There are HTML attributes "width" and "height", but their use is deprecated in favor of using styles. Also, "width" and "height" as HTML attributes can only be numerical values representing pixels - while a CSS style can be many variations(pixels, ems, percentages, etc)
In your specific case, just modify the width styling of your element to change its width.
Another thing in your code is the usage of this and self, which is entirely unneeded. this.videos is setting a property on the global object(window) for no reason. You can also avoid closing over the index property by using .bind():
window.onload = function() {
var videos = document.getElementsByTagName('video');
for (var i = 0; i < videos.length;i++) {
var video = videos.item(i);
video.addEventListener("loadedmetadata", (function () {
console.log(this.offsetWidth);
this.style.width = "480px";
console.log(this.offsetWidth);
}).bind(video));
}
}
Try using getAttribute and setAttribute, as in videos[index].setAttribute('offsetWidth', 480)
First off, this doesn't seem right:
for(var i=0;i<videos.length;i++) {
Shouldn't it be self.videos? Fix that.
Then, to change the video size, you can change the size of the element:
self.videos[index].width = "480";
or, even better, the CSS width:
self.videos[index].style.width = "480px";
The size of the video itself will automatically extend to the size of the video element.
I am making a plugin for form validation as practice, but for some reason after I create a h2 element and try to set it's attribute, it is not working. Here is the code
var testing = function(regex, value, error_msg, error_msg_field_id){
var pattern = new RegExp(regex);
if (!pattern.test(value)){
var ele = document.createElement("H2");
var node = document.createTextNode(error_msg);
ele.setAttribute('style', 'color:white');
alert("hi");
jQuery(error_msg_field_id).append(node);
}
}
the text appears with no problem, but it is not in white color. This make no sense at all to me
You are using setAttribute correctly, but you are setting the property on your h2-element, which is never actually inserted in your DOM.
You can change and simplify the relevant section of your code to:
var ele = document.createElement("H2");
ele.textContent = error_msg;
ele.setAttribute('style', 'color:white');
jQuery(error_msg_field_id).append(ele);
The usage of jQuery here is also not necessary. You can simply use
document.querySelector("#" + error_msg_field_id).appendChild(ele);
which is equally simple.
I have some data coming from the server in which I fill A Div in the Html page with.
The way I write the div is as follows:
<div class="BigDiv"><label class = "AttList" Std_Id="' + Std_Id + '">' + Std_Name +'</label></div>
Now, I want the data inside this div.
There are some other labels inside the div so I use this.children to access this label.
var labels = $(this).children('div');
var StdName = this.children[0].childNodes[0].nodeValue;
I want to access the Std_Id inside the Std_Id attribute, but I don't know how to do it ... Do you have any ideas?
Thanks.
Assuming that $(this) is a reference to the .BigDiv element:
var StdName = $(this).find('label').attr('Std_Id');
Or, similarly, and with the assumption that this is the .BigDiv element:
var children = this.childNodes;
for (var i=0,len=children.length; i<len; i++){
if (children[i].nodeType == 1 && children[i].tagName.toLowerCase() == 'label'){
var StdName = this.getAttribute('Std_Id');
}
}
References:
jQuery:
attr().
find().
JavaScript
element.getAttribute().
node.nodeType.
tagName.
toLowerCase().
Use getAttribute:
var labels = $(this).children('div');
var StdId = this.children[0].getAttribute("Std_Id");
Note that, according to the HTML5 spec, custom attributes should start with data-, though most browsers can tolerate it.
To save elements, which were selected using a jQuery-Selector, do this:
$labels = $('.BigDiv').find('label');
Now you can loop through each label with jQuery's foreach loop:
$.each($labels, function() {
var std_id = $(this).attr('Std_Id');
// do something with std_id
});
You could use the attr method as such,
var value = $('.AttList').attr('Std_Id');
EDIT
OK, so you for your implementation, you need to do this...
var value = $(this).find('.AttList').attr('Std_Id');
Assuming that this is the div or the parent of that div