I am playing around some code where I want to access the element which is created dynamicaaly by script. When I am trying to access this by using getElementById it is responding with
TypeError: ...getElementById is not a function.
code
const testConnectText = "Hello";
const daParent=document.getElementById("test");
const tagDiv = "<p style='text-align: center;'><span class='status' id='connectTest'></span></span></p>";
const statusConnecting = tagDiv.getElementById("connectTest");
statusConnecting = testConnectText;
daParent.innerHTML=tagDiv;
document.body.appendChild(daParent);
any suggestion how to get this and pass the updated text here ?
The getElementById method only exists on the document, rather than on HTMLElements. You can only use document.getElementById, so if you need to find something by id inside a particular element you can use a query selector and a #. However, what you have is not an element but a string. It would be preferable to construct your new HTML by doing something like this:
const p = document.createElement('p');
p.style.textAlign = 'center';
const span = document.createElement('span');
span.classList.add('status');
span.setAttribute('id', 'connectTest');
p.append(span);
Once you've done this, it's possible for you to use p.querySelector('#connectTest') but there wouldn't really be any reason to do that since you already have the span stored in a variable called span.
Using your code as a starting point (not change the way you've chosen to do this), this is your solution.
By moving the accessor to below the call to .innerHTML, the element will be in the DOM. As pointed out. .getElementById() is only available on the document object.
So this shows the simple changes necessary:
const testConnectText = "Hello";
const daParent=document.getElementById("test");
const tagDiv = "<p style='text-align: center;'><span class='status' id='connectTest'></span></span></p>";
daParent.innerHTML=tagDiv;
const statusConnecting = document.getElementById("connectTest");
console.log(statusConnecting.id);
<div id="test"></div>
It should be noted that there can be some security risks using .innerHTML, but that is a topic for a different question.
Related
Snippet of HTML code I need to retrieve values from:
<div class="elgg-foot">
<input type="hidden" value="41" name="guid">
<input class="elgg-button elgg-button-submit" type="submit" value="Save">
</div>
I need to get the value 41, which is simple enough with:
var x = document.getElementsByTagName("input")[0];
var y = x.attributes[1].value;
However I need to make sure I'm actually retrieving values from inside "elgg-foot", because there are multiple div classes in the HTML code.
I can get the class like this:
var a = document.getElementsByClassName("elgg-foot")[0];
And then I tried to combine it in various ways with var x, but I don't really know the syntax/logic to do it.
For example:
var full = a.getElementsByTagName("input")[0];
So: Retrieve value 41 from inside unique class elg-foot.
I spent hours googling for this, but couldn't find a solution (partly because I don't know exactly what to search for)
Edit: Thanks for the answers everyone, they all seem to work. I almost had it working myself, just forgot a [0] somewhere in my original code. Appreciate the JQuery as well, never used it before :-)
The easiest way is to use jQuery and use CSS selectors:
$(".elgg-foot") will indeed always get you an element with class "elgg-foot", but if you go one step further, you can use descendent selectors:
$(".elgg-foot input[name='guid']").val()
That ensures that you only get the input named guid that is a child of the element labelled with class elgg-foot.
The equivalent in modern browsers is the native querySelectorAll method:
document.querySelectorAll(".elgg-foot input[name='guid']")
or you can do what you have yourself:
var x = document.getElementsByClassName("elgg-foot")
var y = x.getElementsByTagName("input")[0];
Assuming you know it is always the first input within the div
You can combine it like this:
var a = document.getElementsByClassName("elgg-foot")[0];
var b = a.getElementsByTagName("input")[0];
var attribute = b.attributes[1].value;
console.log(attribute); // print 41
Think of the DOM as the tree that it is. You can get elements from elements in the same way you get from the root (the document).
You can use querySelector like
var x = document.querySelector(".elgg-foot input");
var y = x.value;
query the dom by selector https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector
var fourty1 = document.querySelector('.elgg-foot input[name=guid]').value;
querySelector will return the first match from the selector. This selector will find the element with class elgg-foot and then look at the input element inside of that for one named guid and then take the value of the selected element.
I think the simplest way would be using JQuery. But using only javascript,
the simplest way would be:
var div = document.getElementsByClassName("elgg-foot")[0];
var input = div.getElementsByTagName("input")[0];
alert(input.value)
Take a look at this JSFiddle here: http://jsfiddle.net/2oa5evro/
Please push me towards a duplicate of this question if possible. I've looked everywhere but can't seem to find it.
How do I do a getElementById on text content?
var test = '<div id="thisDiv">HI</div>';
How do I select thisDiv if it's not a part of the DOM?
Create an element, set your string as its innerHTML and then search inside that ...
Something like
var test = '<div id="thisDiv">HI</div>';
var element = document.createElement('DIV');
element.innerHTML = test;
alert(element.textContent);
(changed the initial outerHTML as you can only maintain a reference to the originaly created element, and not the new one that is created by the new html)
For getting the text value inside your tags, use RegEx:
var re = new RegExp("<(.|\n)*?>", "g");
var content = test.replace(re,"");
You could create a temporary DIV and populate it with your string. Even then, your ability to access it would be limited. Add it to the DOM to access it using getElementById.
var div = document.createElement('div');
div.innerHTML = '<div id="thisDiv">HI</div>';
alert(div.firstChild);
To avoid creating that extra element, we could just add it to the body...
var test = '<div id="thisDiv">HI</div>';
document.querySelector('body').innerHTML = test;
console.log(document.getElementById('thisDiv'));
Obligatory Fiddle
Getting just the text...
console.log(document.getElementById('thisDiv').textContent); // returns HI
I tried to use the method data (jQuery 1.7.1) in this code:
var q = '<div class="form-error-marker"></div>';
var t = $(q).data('message', message).insertAfter(el);
and it does not work.
Note that this works:
var t = $(q).attr('data-message', message).insertAfter(el);
Why does the first variant not work?
EDIT: insertAfter works correctly and new div is added after el (which is instance of one element which I get by getElementById() function; long story short I have a library that I extend).
When I say 'it does not work' I mean that the attribute 'data-message' is not stored.
Using data like that sets an arbitrary piece of data for this node; it doesn't add a new data- attribute. Just add the attribute with the attr function, and then access it with data
var q = $('<div class="form-error-marker"></div>').attr("data-message", message);
Now access it like this:
var message = q.data("message");
Here's a fiddle
When you use jQuery.data you don't change element attributes, instead your data saved in $.cache.
So if you want to change element attributes use jQuery.attr, when you want to save some info use jQuery.data
I'm able to make a div tag using the document.createElement('div')
However i do not know how to give it a unique id.
can anyone help me with this.
I know how to do it using innerHTML however it very cumbersome. (I heard it not a good way of creating a layout.)
Understanding unique as an ID that must not get mixed up with any other ID's in the markup, the easiest way to go is to get the local timestamp. As shown here:
let div = document.createElement("div");
// With old JS syntax
div.id = "div_" + new Date().getTime().toString();
// With ES6 Template Strings you can also write
div.id = `div_ ${new Date().getTime().toString()}`;
Though working with createElement can be a bit of a troublemaker, you should be using some JavaScript framework that solve the tiny little details for you (such as jQuery, Mootools, Dojo, etc.).
var d = document.createElement('div');
d.id = 'myElementId';
d.innerHTML = 'This is the content!';
Or
var d = document.createElement('div')
.id = 'myElementId';
.. same thing really, just a different way of laying it out.
This takes care of assigning the id. Now, for unique. The best way is to use the current time, as it isn't likely to repeat since javascript time is on miliseconds.
Putting it together:
var d = document.createElement('div')
.id = 'id'+new Date().getTime().toString();
This does have the chance to duplicate itself in the right circumstances. If it is is hyper-critical to maintain uniqueness, then the only way is to use a pointer:
// establish a variable to hold the pointer
var uniquePointer = 0;
// every time you use the pointer to create a new element, increment the pointer.
var d = document.createElement('div')
.id = 'id'+uniquePointer;
uniquePointer ++;
You can use a library for this:
https://github.com/LiosK/UUID.js
It "Generates RFC 4122 compliant UUIDs."
Having the element you can assign it the id using the code:
element.id = "somePrefix" + UUID.generate()
var myDiv = document.createElement('div');
myDiv.id = "myUniqueId";
I am trying to convert my jQuery script into javascript. I have a problem there..
I have a script that creates a node
var new_node = document.createElement("div");
new_node.className="tooltip";
new_node.innerHTML = html;
alert(new_node.className);
When i do this
jQuery(link).after(new_node);
It works fine. But I want to do it javascript way. I have tried using appendChild function but it gives some strange results.
Please help me out with this.
You're comparing jQuery's after with appendChild, but they do very different things. after puts the element after the reference element, appendChild puts it inside it.
You probably want insertBefore (with the reference node being link's nextSibling).
So:
var link = /* ... get the `a` element from somewhere ... */;
var new_node = document.createElement("div");
new_node.className="tooltip";
new_node.innerHTML = html;
link.parentNode.insertBefore(new_node, link.nextSibling);
If link is the last thing in its parent, that's fine; link.nextSibling will be null and insertBefore accepts null as the reference node (it means "insert at the end").
Assuming you already have a node instantiated as link, you could do what you want this way in plain Javascript:
link.parentNode.appendChild(new_node);
The link node would have to be the last node in its container. Otherwise you would have to find link's nextSibling and use insertBefore to put new_node in its proper place.
jQuery(link).append(new_node);