This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 6 years ago.
I created a .js file for the directory of html of files I am working with. The purpose of the .js file is to remove element ids. So in my .js file I currently have the script
var element=document.getElementById("id1");
element.parentElement.removeChild(element);
which works perfectly fine and does what I need to do. Now If I was to include an additional script to remove the id element of a different html page
var element = document.getElementById("id1");
element.parentElement.removeChild(element);
var elem = document.getElementById("id2");
elem.parentElement.removeChild(elem);
Only the first script is executed and the second is not in addition I receive the message "Uncaught type error: cannot read 'parentElement' of null. I would think that each html page would read the .js file and match the corresponding element it is referring too and make the change.
Uncaught type error: cannot read 'parentElement' of null means that it could not find the element with the given id and therefore you can not try to find its parent element. If you wanted to make this more generic you could try abstracting it to a function
function removeElementById(elId) {
var el = document.getElementById(elId);
if (el) {
el.parentNode.removeChild(el);
}
}
Now whenever you try to remove an element it will first check that it is not "falsy" before attempting to remove the element from its parent.
It's like the error says, the parentElement of a non existing element is null, and null has no method 'removeChild' So you must check if element exists.
var element=document.getElementById("id1");
if(element) {
element.parentElement.removeChild(element);
}
The element (id2) you tried to find is probably not in DOM when the srcipt runs. You will need to check if it is null before accessing its methods.
Related
as much as the question seems silly (and in fact it is) I didn't find the answer anywhere, only what I find is answers to know if the element already exists in the DOM (which would solve my problem, but that would be a way unprofessional to solve).
Here is my code ex :
function randomName(element) {
// Im trying to find some method like this:
const result = isElement(element) ? true : false
}
You might want to check if the variable is an instance of HTMLElement. So basically
function isElement(element){
return element instanceof HTMLElement;
}
Also check the mdn-docs, because it's possible that you want to check if your element is a Node (would include text-only nodes) or just an Element (that would include XML-tags in an XML document).
I have a table in which I want to extract the text of the active item. I do this with the following code:
var addedWorkout = $("#custDropDownMenuA").find(".dropdown-item.active");
console.log(addedWorkout);
addedWorkout = addedWorkout.textContent;
console.log(addedWorkout);
The problem is that I keep getting undefined. I checked the console and it indeed finds the element I want without fail.
I am relatively new to Javascript, but after over an hour of Googling I could not find the issue and I don't understand why. I know that I can get the text element if I hardcore it using the following line:
document.querySelector("#selectiona1").textContent
but not with:
$("#selectiona1").textContent
What is the difference between these 2? I read that textContent is part of the DOM, to my understanding it relates to objects and according to my console i think it is an object. I made some crazy attempts like putting the object I got into the querySelector, but nothing works.
With this line:
var addedWorkout = $("#custDropDownMenuA").find(".dropdown-item.active");
you're using jQuery to select the .dropdown-item.active inside #custDropDownMenuA, and when you select with jQuery, you get a jQuery object in response. So, addedWorkout is a jQuery object, and jQuery objects generally do not have the same properties/methods as standard HTMLElements. (querySelector is the vanilla Javascript method to retrieve an element)
Either select the [0]th item in the jQuery collection to get to the first matching element:
var addedWorkout = $("#custDropDownMenuA").find(".dropdown-item.active")[0];
Or use the jQuery method to get the text of the first matching element, which is .text():
var addedWorkoutText = addedWorkout.text();
(note the use of a new variable - you will likely find it easier to read and debug code when you create new variables rather than reassigning old ones, when possible)
Your var 'addedWorkout' is a Jquery object, not a html element.
To show the text use:
addedWorkout.text();
Alternatively, you can change the 'addedWorkout' to a html element by adding the index [0], like this:
addedWorkout[0].textContent;
EDIT:
JSFIDDLE here. I am trying to mirror DESKTOP 1 to MOBILE 1 elements (same for #2) in the fiddle. The error is shown in console.
Got to DESKTOP 1 and select NEW RATE from the list. Have the console opened to see the issue. Thanks!
I get an element from my layout with this command:
var eqTaxSelect = $('table#mob-tab-' + num).find('select.tax_rate').get();
I then try to toggle it:
toggleField($(eqTaxSelect), $(eqTaxSelect).nextElementSibling); <-- FAILS
function toggleField(hideObj, showObj) {
hideObj.style.display = 'none'; <-- FAILS HERE
showObj.style.display = 'inline';
showObj.focus();
}
with:
Uncaught TypeError: Cannot set property 'nextElementSibling' of undefined
What am I doing wrong when assigning the element to my variable? This function works for this inside click event listeners for example.
Thanks!
The HTML I am toggling came from this forum, essentially a select with a hidden input so new entries can be added as well as using an entry from the options list.
What am I doing wrong when assigning the element to my variable?
You are passing jQuery() objects, where toggleField expects DOM elements. jQuery() does not have a .nextElementSibling method. Remove calls to jQuery() at
toggleField($(eqTaxSelect), $(eqTaxSelect).nextElementSibling);
replace with
toggleField(eqTaxSelect, eqTaxSelect.nextElementSibling);
to pass DOM elements to toggleField.
test with
console.log(eqTaxSelect)
see on inspector (CTRL+SHIF+I CHROME). if this is ok,
just do this
toggleField(eqTaxSelect, eqTaxSelect.nextElementSibling)
withouth "$"
The reason why your statement
toggleField(eqTaxSelect, eqTaxSelect.nextElementSibling);
fails is because of the way you are populating the eqTaxSelect
var eqTaxSelect = $('table#mob-tab-' + num).find('select.tax_rate').get();
It should be modified as
var eqTaxSelect = $('table#mob-tab-' + num).find('select.tax_rate').get(0);
reason being, get() without an index returns an array and the way you are operating, you are expecting an single dom element.
jQuery documentation for get()
This question already has answers here:
full HTML of object returned by jQuery selector
(10 answers)
Closed 8 years ago.
Let's say I have some elements like:
<div id="some-id" class="some-class">
<h1>Something here</h1>
</div>
And I would like to copy the whole some-id element together with all it's children, send it to database and then, when reloading the page, append them to the body.
I tried:
clone() and I got: "prevObject: jQuery.fn.jQuery.init[0], context: undefined, constructor: function, init: function, selector: ""…"
cloning and JSON.stringify() and I got one warning and one error in the console:
'Attr.ownerElement' is deprecated and has been removed from DOM4 (http://w3.org/tr/dom).
Uncaught TypeError: Converting circular structure to JSON
What can I use to end up with the html structure of my element that I can put in the database and re-use it?
If you want to persist a html structure, then you need to use its html string, you can't stringify the dom reference. The html string can be saved and can be used later to append back to the dom.
var string = $('#some-id')[0].outerHTML
Use outerHTML :
document.getElementById('some-id').outerHTML
jQuery clone should do the job. Try this:
var elem = $('#some-id');
var clone = elem.clone();
Besides, why are you saving it to the DB?
I am trying to get to a element (using javascript) which is inside UIAElementArray that has a number name like 1.
So when I try to get the element say with
array()["1"]
I am still getting the element at the index 1, instead of element which has a name/key value of 1.
Before some of you shoo me off to apple documentation, I found this and tried using firstWithName and withName
array().firstWithName("1")
but now I am getting a weird error "-[__NSCFNumber length]: unrecognized selector sent to instance 0x7c81ab0"
I haven't used length explicitly anywhere, what does the error mean and how do I get out of this?
I do not know exactly regarding the error but I know how to get required element. Try this one:
var predicate = "name contains '1'";
var requiredObj = mainWindow().popover().staticTexts().firstWithPredicate(predicate);
Hope this will help.