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.
Related
So in essence I get the value of input, then try to divide into into different tags via the comma with this
var noteTags = document.getElementsByClassName("noteTag").value;
Tag = noteTags.split(",");
But in console, the split(",") is undefined
Edit: Sorry I forgot to mention that the noteTag element is input, does this change how the code works in any way?
There are two issues,
getElementsByClassName returns an array-like collection of elements (a NodeList).
And instead of value it should be innerText.
Try like below
var noteTags = document.getElementsByClassName("noteTag")[0].innerText;
Tag = noteTags.split(",");
You are using the split() method on an array. You are also trying to access the value property, whereby you should probably use innerText.
You can use querySelector then you dont need using a key[0] to select the element.
const noteTags = document.querySelector("#noteTag");
console.log(noteTags)
Tag = noteTags.innerHTML.split(",");
console.log(Tag)
<div id="noteTag">en,jp,fr</div>
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`)
// −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−^
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 new to js.
can you tell me why I am getting empty values for sports-title and third.
since we have one div with content in it.
sports-title---->{"0":{}}
third---->{}
providing my code below.
findStringInsideDiv() {
/*
var str = document.getElementsByClassName("sports-title").innerHTML;
*/
var sportsTitle = document.getElementsByClassName("sports-title");
var third = sportsTitle[0];
var thirdHTML = third.innerHTML
//str = str.split(" ")[4];
console.log("sports-title---->" + JSON.stringify(sportsTitle));
console.log("third---->" + JSON.stringify(third));
console.log("thirdHTML---->" + JSON.stringify(thirdHTML));
if ( thirdHTML === " basketball football swimming " ) {
console.log("matching basketball---->");
var menu = document.querySelector('.sports');
menu.classList.add('sports-with-basketball');
// how to add this class name directly to the first div after body.
// but we are not rendering that div in accordion
//is it possible
}
else{
console.log("not matching");
}
}
When you call an object in the Document Object Model (DOM) using any of the GetElement selectors, it returns an object that can be considered that HTML element. This object includes much more than just the text included in the HTML element. In order to access the text of that element, you want to use the .textContent property.
In addition, an HTML class can potentially be assigned to several elements and therefore GetElementsByClassName returns an array so you would have to do the following, for example:
console.log("sports-title---->" + JSON.stringify(sportsTitle[0].textContent));
You can find a brief introduction to the DOM on the W3Schools Website. https://www.w3schools.com/js/js_htmldom.asp If you follow along it gives an overview of different aspects of the DOM including elements.
Maybe this would be helpful
As you see sportsTitle[0].textContent returns full heading and 0 is the index thus you get "0" when you stringify (serialize) sportsTitle. Why 0? Because you have one <h1> element . See this fiddle http://jsfiddle.net/cqj6g7f0/3/
I added second h1 and see the console.log and you get two indexes 0 and 1
if you want to get a word from element so get substring use substr() method https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substr
One way is to change <h1> class attr to id and do sportsTitle.textContent;
and use substr() on this string
or
2nd way is to remain class attr and do sportsTitle[0].textContent;
and substr() on this string
The 2nd is the better way
Assuming I have this:
var wrap = $("#someId");
I need to access the original object that I would get by
var orig = document.getElementById("someId");
But I don't want to do a document.getElementById.
Is there something I can use on wrap to get it? something like:
var orig = wrap.original();
I searched high and low but I didn't find anything; or maybe I'm not looking for the right thing.
The function for this is get. You can pass an index to get to access the element at that index, so wrap.get(0) gets the first element (note that the index is 0-based, like an array). You can also use a negative index, so wrap.get(-2) gets the last-but-one element in the selection.
wrap.get(0); // get the first element
wrap.get(1); // get the second element
wrap.get(6); // get the seventh element
wrap.get(-1); // get the last element
wrap.get(-4); // get the element four from the end
You can also use array-like syntax to access elements, e.g. wrap[0]. However, you can only use positive indexes for this.
wrap[0]; // get the first element
wrap[1]; // get the second element
wrap[6]; // get the seventh element
$("#someId") will return a jQuery object, so to get at the actual HTML element you can do:
wrap[0] or wrap.get(0).
You can use get() to retrieve the HTML element.
var orig = wrap.get(0);
However, if wrap consists of multiple elements, you will need to know the correct index which to use when you use the get() function.
You can just use var orig = wrap[0]; as far as I know, if there's more than one element. If there's just the one, you can just use wrap without $() around it.
You can use wrap still.. Wrap is the same as 'orig' would be in the above! :)
If you really want:
var orig = wrap;