How can i click button based on text instead of Class - javascript

I can't edit this code to work in buttons based on text instead of class or make it for both by class name and text.
For example:
<button class="same">plz-click-me</button>
<button class="same">dont-click-me</button>
Now I want code to click on the "click-me" button
This what I used in my code to click by class
var inputs = document.querySelectorAll('.same:not(.hidden_elem)');
Thanks and hope to find answers help me

You'll have to iterate through the possible matching elements and select those whose textContent matches what you want. You can't use jQuery's .contains because the substring click-me is included in don't-click-me:
const matching = Array.prototype.filter.call(
document.querySelectorAll('.same'),
({ textContent }) => textContent === 'click-me'
);
console.log(matching);
<button class="same">click-me</button>
<button class="same">dont-click-me</button>
Note that if the substring of the one you want to select is not included in the elements you don't want to select, you can use .contains:
$('.same:contains("click-this-here")').click(() => console.log('clicked'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="same">click-this-here</button>
<button class="same">dont-click-me</button>

var buttons = document.querySelectorAll("button");
var clickButton = Array.from(buttons).filter( button => button.textContent === "click-me")[0];
<button class="same">click-me</button>
<button class="same">dont-click-me</button>

Related

How do I add a delete button next to my task list?

This is what i have right now, what code do i add to make buttons next to my tasks, so with every new task there must come a remove button as well
document.getElementById('submit').addEventListener('click', withClick);
function withClick(e) {
const li = document.createElement('li')
document.getElementById('listid').appendChild(li);
li.appendChild(document.createTextNode(document.getElementById("text-area").value))
li.id = 'list'
li.className = 'collection-item'
const button = document.createElement('button')
document.getElementById('list').appendChild(button);
button.appendChild(document.createTextNode('x'))
button.className = "button"
}
<ul id="listid">
</ul>
<input id="text-area">
<button id="submit">submit</button>
This is what it looks like in browser
id needs to be unique in HTML.
Currently every <li> element you create has id="list". So when you do this:
document.getElementById('list')
Which one do you expect it to find and why? The behavior is likely undefined, but what you're observing is that it finds the first one with that id and then stops searching. Because why wouldn't it? Once it finds the element with the target id, as far as the browser is concerned it has found the one target element you're looking for.
Instead of fetching the element by its id, you already have a reference to it in the li variable. Just use that:
document.getElementById('submit').addEventListener('click', withClick);
function withClick(e) {
const li = document.createElement('li')
document.getElementById('listid').appendChild(li);
li.appendChild(document.createTextNode(document.getElementById("text-area").value))
li.className = 'collection-item'
const button = document.createElement('button')
li.appendChild(button); // <---- here
button.appendChild(document.createTextNode('x'))
button.className = "button"
}
<ul id="listid">
</ul>
<input id="text-area">
<button id="submit">submit</button>

Problem with Dom-event to an array of buttons

I am trying to create a visual element where you can add and remove 2 input fields and a p element, while I found a way to do it, While removing them not in chronological order the last div wont be removed and prints me "cant remove of undefied"
I tried doing it in a few ways, through if function, throgh array methods etc... always the same problem
so the Html code goes this way
<main id="mainBlock">
<div class="divBlock">
<input class="name" type="text">
<input class="workingHours" type="text">
<p class="money"></p>
<button class="deleteButton">delete</button>
</div>
<button id="addButton">add</button>
</main>
and the js:
let addButton = document.getElementById('addButton');
let allDivs = document.getElementsByClassName('divBloc');
addButton.onclick = function(){
let deleteButtons = document.querySelectorAll('button.deleteButton');
let allDeleteButtonsArr = Array.from(allDeleteButtons)
allDeleteButtonsArr.forEach(item => {
item.onclick = function(){
let indexNumber = allDeleteButtonsArr.indexOf(item);
allDivs[indexNumber].remove();
};
});
I think i should explain while the onclick function is related to the create button at first. For the purpose of giving you easier time to read I delete all the part where I create all the new p div and input elements when you click on it. because each time you click on add element there is a new index number I thought it will be better to include it inside the addButton onclick fucntion.
Thanks in advance :)
Since you're dynamically appending nodes, and then you wish to remove them, adding/removing event handlers to the delete button might be very annoying.
A better way is to use event delegation by adding the event listener to the container #mainBlock, and when it's called check if the the delete button was called, and if so remove it's parent.
const item = `
<div class="divBlock">
<input class="name" type="text">
<input class="workingHours" type="text">
<p class="money"></p>
<button class="deleteButton">delete</button>
</div>
`;
const container = document.querySelector('#mainBlock');
const addButton = document.querySelector('#addButton');
addButton.addEventListener('click', () => {
addButton.insertAdjacentHTML('beforebegin', item);
});
container.addEventListener('click', e => {
if(!e.target.matches('.deleteButton')) return;
e.target.parentNode.remove();
});
<main id="mainBlock">
<button id="addButton">add</button>
</main>

How do I access a specific element in the inner HTML?

I am trying to use JS or jQuery to access an html value called "data-button". I can access the whole HTML div and pull out class name as well as the text content from the button, but I cant get the data-button value.
In the code below I have a captureRecipeButtons() function that can get the "recipe-1-container" div.
function captureRecipeButtons(){
let theWholeDiv = document.getElementsByClassName("recipe-1-container")[0];
let buttonValue = ?;
}
<div class="recipe-1-container">
<button class="listed-recipe-link" data-button="1">Element</button>
</div>
In my captureRecipeButtons() function I want buttonValue to equal "1" in my above code. Any help would be appreciated thanks.
You can use the full power of CSS selectors with querySelector:
function captureRecipeButtons(){
let button = document.querySelector(".recipe-1-container [data-button]");
}
querySelector returns the first matching element (or null if none do).
If you wanted the value of data-selector on that element, then getAttribute or dataset:
function captureRecipeButtons(){
let buttonValue = document.querySelector(".recipe-1-container [data-button]").getAttribute("data-button");
// or
let buttonValue = document.querySelector(".recipe-1-container [data-button]").dataset.button;
}
Live Copy:
function captureRecipeButtons(){
const button = document.querySelector(".recipe-1-container [data-button]");
console.log(button.getAttribute("data-button"));
// or
console.log(button.dataset.button);
}
captureRecipeButtons();
<div class="recipe-1-container">
<button class="listed-recipe-link" data-button="1">Element</button>
</div>
But note that dataset does some transformations.
But there are lots of different ways to do this. More to explore in the DOM.
So you could just get the button element by class or tag name as I have done. then data-button is legit just an attribute so just use getAttribute('data-button');
The way I've written below will just get the first button that is a direct child of theWholeDiv element.
function captureRecipeButtons(){
let theWholeDiv = document.getElementsByClassName("recipe-1-container")[0];
let buttonValue = theWholeDiv.getElementsByTagName('button')[0].getAttribute('data-button');
console.log(buttonValue);
}
captureRecipeButtons();
<div class="recipe-1-container">
<button class="listed-recipe-link" data-button="1">Element</button>
</div>
According to Mozilla Docs,
You can access the Data attributes via the dataset object.
function captureRecipeButtons(){
let theButton = document.querySelector("recipe-1-container > button");
let buttonValue = theButton.dataset.button;
}
Another way using the DOM, including some short-cuts to avoid excessive horizontal scrolling. The code precisely targets the first DIV element and its first BUTTON element, using the getAttribute() method to return the value of the indicated property. What is nice about JavaScript is the fabulous amount of chaining that one can do between parent and child elements.
function captureRecipeButtons() {
let d = document;
d.g = d.getElementsByTagName;
let buttonValue = d.g("div")[0].getElementsByTagName("button")[0].getAttribute("data-button");
console.log(buttonValue);
};
captureRecipeButtons();
<div class="recipe-1-container">
<button class="listed-recipe-link" data-button="1">Element</button>
</div>
Alternatively, you could write code as follows:
function captureRecipeButtons() {
let d = document;
d.g = d.getElementsByTagName;
let button = d.g("div")[0].childNodes[1];
button.g = button.getAttribute;
let buttonValue = button.g("data-button");
console.log(buttonValue);
}
captureRecipeButtons();
<div class="recipe-1-container">
<button class="listed-recipe-link" data-button="1">Element</button>
</div>
The DIV element's first child node as per the format of the code is not the BUTTON element but a text object. The childNode[1] holds the BUTTON element, so you can use its getAttribute() method to retrieve the value of the data-button attribute.

Disable certain buttons javascript when id's are different

I want to disable a certain group of buttons at a specific time. Using this js:
document.getElementById("reset").setAttribute('disabled','disabled');
But all IDs are different, the buttons is like <button id=1> <button id=2> etc. Can I set some made up variable like <button group="hello">
And then do something like this:
document.getElementById("group:hello").setAttribute('disabled','disabled');
to disable all of the buttons, even though the ID attribute is different from button to button?
what you can do is use the data attribute, see next:
<button data-group="hello" id="button1">test1</button>
<button data-group="hello" id="button2">test2</button>
<button data-group="hello" id="button3">test3</button>
and the JS
document.querySelectorAll('[data-group="hello"]').forEach(function(button) {
button.disabled = true;
});
edit, here is the fiddle https://jsfiddle.net/xycmj4gv/2/
Use class instead of ID.
Code is easy:
document.getElementsByClassName("group1").setAttribute('disabled','disabled');
Since you tagged jquery
$(".mybutton").attr("disabled", true);
Where mybutton is
<button class= "mybutton"> </button>
Use class instead of id as follows:
var elements = document.getElementsByClassName("{yourClassName}");
var i;
for (i = 0; i < x.length; i++) {
elements[i].setAttribute(“disabled”, “red");
}
<button class="{yourClassName}”></button>
You can use getElementsByTagName to get all buttons and then You can use Array.Prototype.forEach to disable all buttons like below. forEach will loop through all element and add desired attribute(in your case disabled) to all found elements.
Array.prototype.forEach.call
(document.getElementsByTagName("button"), function(e) {
e.setAttribute('disabled','disabled');
});
<button id="1">12</button> <button id="2">12</button>
<button id="3">12</button> <button id="4">12</button>
You can use wildcards for Id's:
Starts-with selector
document.querySelector("[id^=myId]")
works for
id="myId1"
id="myId2"
...
or Ends-with selector
document.querySelector("[id$=myId]")
works for
id="firstMyId"
id="secondMyId",...
Hint:
Please don't start Id's with numbers like: id="1myId". That's not w3c conform
use class to group buttons, like this:
var btnsGroup = document.getElementsByClassName('group');
Array.prototype.forEach.call(btnsGroup, function(button) {
button.setAttribute('disabled','disabled');
});
You can do something like this-
var buttons = document.querySelectorAll("[reset='true']");
for (i = 0; i < buttons.length; ++i)
{
buttons[i].setAttribute('disabled','disabled');
}
And HTML goes like this-
<button reset="true" >1 Candy</button>
<button reset="true" >2 Candy</button>

How to change button color onclick using javascript only?

I was trying to make the color of the buttons change using onclick and getElementsByClassName and came up with something like this:
HTML:
<button onclick="submitButtonStyle()" type="submit" class="stylebutton">
Submit </button>
JS:
function submitButtonStyle() {
document.getElementsByClassName("stylebutton").style.backgroundColor = "red"; }
I would be really grateful if you guys gave me a hint about what is lacking in my code/what I should add etc.
getElementsByClassName returns an HTMLCollection so you need to get the elements using an index, in your case index === 0 getElementsByClassName[0].
Actually, you don't need to call the function getElementsByClassName, pass the element as param.
function submitButtonStyle(_this) {
_this.style.backgroundColor = "red";
}
<button onclick="submitButtonStyle(this)" type="submit" class="stylebutton">
Submit </button>
Better approach using Event binding and function querySelectorAll
document.querySelectorAll('.stylebutton').forEach(function(e) {
e.addEventListener('click', function() {
this.style.backgroundColor = "red";
})
});
<button type="submit" class="stylebutton"> Submit </button>
document.getElementsByClassName returns an array of objects, since many tags may have the same class. If you know that only one object has a given class, use
document.getElementsByClassName("stylebutton")[0].style.backgroundColor = "red";
The className property sets or returns the class name of an element (the value of an element's class attribute).
function submitButtonStyle() {
document.getElementsByClassName("stylebutton")[0].style.backgroundColor = "red"; }
<button onclick="submitButtonStyle()" type="submit" class="stylebutton">
Submit </button>
JS:
The getElementsByClassName() method returns a collection of all
elements in the document with the specified class name, as a NodeList
object.
The NodeList object represents a collection of nodes. The nodes can be
accessed by index numbers. The index starts at 0.
Source
Using jquery, try this. if your button id is say id= clickme
$("clickme").on('çlick', function(){
$(this).css('background-color', 'grey'); .......

Categories