I have the following code:
$("#modal-bool-element").change(function(e) {boolSettings($(e.target))});
function boolSettings(e) {
elem = e;
var boolSettingsParent = elem.closest("#bool-settings");
if (elem.is(":checked") == true) {
elem.val(true);
boolSettingsParent.find("#modal-bool-show").prop("disabled", false);
} else {
elem.val(false);
boolSettingsParent.find(".bool-reset, .bool-offset").hide();
boolSettingsParent.find("#modal-bool-show").val("never");
boolSettingsParent.find("#modal-bool-show").prop("disabled", true);
boolSettingsParent.find("#modal-bool-offsetValue, #modal-bool-reset, #modal-bool-offsetUnit").val("");
}
}
What I would like to do is to pass the value of an atrribute to find method along with the classname or id. That attr is elem.attr("model-id").
I have tried like this:
boolSettingsParent.find(`#modal-bool-show [model-id='{elem.attr(model-id)}']`)
But I am not getting any value. How can I achieve the desired result?
Remove the space:
boolSettingsParent.find(`#modal-bool-show[model-id='{elem.attr(model-id)}']`)
// −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−^
The space means you're looking for a descendant element of #modal-bool-show with that attribute. Without the space, it means you only want #modal-bool-show if it also has that attribute value.
You mentioned a class but haven't shown picking one. To do that, you'd tack on a class selector:
boolSettingsParent.find(`#modal-bool-show[model-id='{elem.attr(model-id)}'].some-class`)
// −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−^^^^^^^^^^^
BUT, just the id should be sufficient unless you want to skip the element if it doesn't have that attribute and/or class, because you can't have more than one element in the DOM with the same id — doing so is invalid. So adding more things to the selector is fine if you want the selector not to match anything if the element with that id doesn't have the attribute and/or class, but if you're doing it so the selector matches the "right" element with that id, that's a problem because it means you have more than one element with the same id.
I assumed in the above that you were using some templating system that handled the {...} for you, but if you meant to use a substitution in JavaScript's template literal, they use the format ${...}, not {...}. So:
boolSettingsParent.find(`#modal-bool-show[model-id='${elem.attr(model-id)}'].some-class`)
// −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−^
Related
I need a help. I have a button in html with class "rekapitulace". And i want to do if a user click on that button, it will show a item in text input with class "jmeno". I wrote this but it isnt correct. Any solutions?
function rekapitulaceButton() {
var rekapitulaceButton = document.getElementsByClassName('rekapitulace')
rekapitulaceButton.addEventListener('click', precistUdaje)
}
function precistUdaje() {
var jmeno = document.getElementsByClassName('jmeno')
localStorage.setItem('local-jmeno', jmeno)
console.log(localStorage.getItem('local-jmeno'))
}
getElementsByClassName() returns all elements of provided class name, not just a single element. Notice how the name of that method contains plural elements word.
To get the first element, you can do:
const rekapitulaceButton = document.getElementsByClassName('rekapitulace')[0];
Another possibility is document.querySelector(), which always returns one element (first match) or null:
const rekapitulaceButton = document.querySelector('.rekapitulace');
document.getElementsByClassName('rekapitulace') return a nodelist array so if you need return an one node elment using id instead of class
document.getElementById('rekapitulace')
Note that you may be misusing localStorage for your debugging. The second argument of .set should be a string.
As mentioned already, you should really try to use IDs instead of classes for targeting the right input, and document.getElementsByClassName returns multiple elements and not just one element.
I am trying to use javaScript to determine if an element with a specific class name exists on an html page. The element in question is only sometimes loaded on the page.
When I use document.getElementsByClassName('element-in-question').innerHTML = "Hello"
It will work when the element exists, but when it doesn't exist, it will return as "cannot set property of innerHTML of undefined and the rest of the code will not run.
Is there a way to check if an element exists, and only modify it when it does without breaking the rest of the code?
Thanks for the help
You can also use document.querySelector which will return the first element within the document if it exists, if not, it returns null.
const targetElement = document.querySelector('.element-in-question');
if (targetElement) {
targetElement.innerText = 'Hi there!';
}
<div class="element-in-question"></div>
Tip: If you're just adding text consider using innerText instead of innerHTML.
Just wrap you code with if statement :
const elemts = document.getElementsByClassName('element-in-question');
if(elemts.length) {
// this actually need to be elemts[0].innerHTML
elemts.innerHTML = "Hello"
}
Note: document.getElementsByClassName will return array/collection of elements so if you really know that there is no other elements keep using it otherwise switch to getElementById.
as per documentation:
The getElementsByClassName() method returns a collection of all
elements in the document with the specified class name, as an
HTMLCollection object.
It's very simple with the condition IF
If you want to get elements by class, the function will return an array (a collection of all elements in the document with the specified class name), so you will check as following :
if (document.getElementsByClassName('class-in-question').length > 0) {
// Existed
}
If you want to get an element by specified id, the function will return an objet HTML with that id, so you will check as following :
if (document.getElementById('id-in-question')) {
// Existed
}
I am trying to Get First Child with classname Plain Javascript.
I am trying to write my own form validation and trying the error message i appended and remove it. As well as dont append if error message is already there.
If you help me with just the first part getting child with class name that whould be great.
function display_error(selector, message) {
selector.insertAdjacentHTML('afterend', "<h1 class='js-error' >" + message + "</h1>");
}
function validateForm() {
// Validate Name Field
// Check if name has les than 3
var elem = document.getElementById("name")
if (elem.value.length < 3) {
display_error(elem, "Less than 3")
return false;
} else {
// here is the error
error_label = elem.querySelector('.js-error');
error_label.textContent = "more than 3"
}
}
here is a fiddle
https://jsfiddle.net/efh941cc/3/
The beautiful thing about document.querySelector() is that you can use CSS selectors rather than the, often clunky, DOM API.
CSS provides a very simple selector called first-child which does exactly what you need.
// Find the first element that uses the .test class that is a child of another element.
var firstTest = document.querySelector(".test:first-child");
// Now that you've scanned and found the element and stored a reference to it
// in a variable, you can access any aspect of the element.
console.log(firstTest.textContent);
firstTest.innerHTML = "<span>Now, I have completely different content than before!</span>";
// Now, we can get a reference to other elements that are relative to the last
// one we found.
var firstTestError = document.querySelector(".test:first-child + .error");
firstTestError.style.backgroundColor = "aqua";
firstTestError.innerHTML = "<span>Required</span>";
<div>
<span class="test">one</span><span class="error"></span>
<div class="test">two</div>
<div class="test">three</div>
</div>
In modern JavaScript, to get the first child with a class name, you can use the following:
document.querySelector('element.class:first-child')
Here, you supply the actual element, and the actual class name.
document.querySelector is available in all modern browsers, and will take any string which matches a CSS selector. It even works in IE8, though the :first-child pseudo class is not available there.
const GetFirstChild = document.querySelector(' .PlainJavascript');
Simply, i'm trying to use jQuery to append a numeric value (currently stored in an array) to the end of the "id" attribute of a number of specified elements.
$('#headerAfirstLink, #headerAsecondLink, #headerAthirdLink, #headerAfourthLink').attr("id", // Append modCount[0].toString() to each existing ID);
The struggle I am having is in working out how to append the numeric value as opposed to simply set the ID equal to the numeric value. I don't want to lose the existing ID.
In the example, the preferred resulting ID's should be:
#headerAfirstLink1, #headerAsecondLink1, #headerAthirdLink1, #headerAfourthLink1
(If modCount[0] == 1).
I'm sure it is crucifyingly simple but would appreciate some guidance.
Thanks
You can use .attr(attributeName, function) syntax to update the attribute value for each of the respective element.
$('#headerAfirstLink, #headerAsecondLink, #headerAthirdLink, #headerAfourthLink')
.attr("id", function(index, oldId) {
// oldId is the attribute value
return oldId + modCount[0];
});
Just in case, to update the attribute of all the elements whose ID starts with header, you can use attribute starts with selector.
$('[id^="header"]').attr('id', function(index, oldId) {
return oldId + modCount[0];
});
Try to use .attr("attrName" , callBack) signature to achieve what you want.
$('#headerAfirstLink, #headerAsecondLink, #headerAthirdLink, #headerAfourthLink')
.attr("id", function(_,id){
return id + modCount[0];
});
Don't confuse the first parameter passed with callBack. It is index. I just used an underscore there as it is not required in our case. Simply to hide its visual.
Or the best/maintainable approach would be setting a common class (ex: test) to those four elements and use a class selector there instead of multiple selector.
$('.test').attr('id', function(_, id) {
return id + modCount[0];
});
In my HTML file, I want to set a check box with specific name as well as id as= checked. How can I acheive this..?
eg:
<input type="checkbox" name="myName_1" id="1" value="my Value 1"> my Value 1
I know document.getElementById('id').checked = true;, but this only checks id. I need to check for id and name simultaneously using JavaScript. Pls help.
Edit:
More specific:
if(document.getElementById(1) && document.getElementById(1).type == "checkbox" ){
document.getElementById(1).checked = true;
}
Note: I have other elements that have same id, but different name, as well as same name, but different id. But no two have both in common.
Well, as i said IDs are always unique in the DOM. So having elements with the same ID is not valid.
You can however select by the name attribute with getElementsByName as this selection supports multiple element. It will just create a array that you can acces through the index value. So you can just loop through all the element and check them one by one:
var elem = document.getElementsByName('myName_1');
for(var i = 0; i < elem.length; i++)
{
elem[i].checked = true;
}
jsFiddle
Having id of HTML elements, starting with a number is incorrect. Rename your id and make it unique. Also value of id of 1 evaluates to true by javascript engine.
However if your HTML document is HTML5 compliant then id starting with a number is not problem.
You could do something like this, not ideal, but would solve the problem.
var names = document.getElementsByName(nameToFind);
names.forEach(funciton(item) {
if (item.id == idToFind)
item.checked = true;
});
As mentioned by several comments, it is not valid to have more than one element with the same id. If there are more than one of the same id, the behavior is unreliable.
If you have groupings of elements that are similar, a common convention with many developers is to give them a common class. This could/would replace your use of name. You can then search on elements within a certain class that have a specific id. (Which may be redundant, depending on your use.)
Searching by class is done with document.getElementsByClassName("myClass"), which returns an array of elements, similar to getElementsByName. Once you have this array, you can then loop through to determine if your id is within that class group[see note below] and apply effects as necessary. (e.g. elementArray[i].checked = true)
Note - It would be much more efficient to search for the id then determine the class, in my opinion.